About Random HTML Ids

Sometimes, it's useful to generate random ids for HTML widgets, such as tabs, collapsible items, or modal dialogs. Here's how you can do this:

1
2
3
4
5
6
7
def generate_random_id(prefix):
    import string
    import random
    random_string = "".join(
        random.choices(string.ascii_uppercase + string.digits, k=8)
    )
    return f"{prefix}_{random_string}"

Tips and Tricks Development Django 4.x Django 3.2 Django 2.2 Python 3