Where to put start-up function

I would like to check that certain groups exist in the database after Django starts. If not, the code creates those groups

For example:

from django.contrib.auth.models import Group

def prepare_user_groups():
    """Check that Groups exist, and if not create them"""

    group_names = [
        "SysAdmins",
        "Owners",
        "Administrators",
        "Sales",
        "Accounts",
        "Staff",
    ]

    for name in group_names:
        if name not in Group.objects.all().values_list("name", flat=True):
            Group.objects.create(name=name)

Where should I put this kind of thing? In the app/models.py or … ?

project/urls.py
It will be ran when the server starts or reloads.

See the thread at How to automatically create model instances during boot-up?

If it is a one time operation, another option is to implement that as a data migration.

Interesting discussion there.

I like the option of custom Django Management Commands. I am still somewhat confused about file structure.

In a structure like so:

project_root
    |- project_folder
    |- app_1
    |- app_2
    |- app_3
    |- manage.py

Where should the management folder reside – inside one of the app_x folders or on the same level with manage.py. Most tutorials out there are not explicit.

Here explains the file structure for commands for an app named polls

1 Like

In your case it will be app_1 or app_2 or app_3, instead of polls