Sayantan Das Sayantan Das - 9 months ago 23
Python Question

How to create groups and assign permission during project setup in django?

I know I can create user groups and assign permission to them from the admin area in a django project. I can also create a group and assign permission to it by importing

Group
and
Permission
model from django's auth module.

What I want to know if there is any way I can create group and assign permission to them when I set up the project. So, if I have types of users, Admin, Developer, Tester and Project Manager. They are basically user groups which would have different permission level. I did not customize the
User
model and only can differentiate by the groups they are assigned to. So is there a way to create these groups and assign required permission to them like when permissions are created for admin when I run
python manage.py migrate
?

Answer Source

You can define a post_migrate signal to create required User and Group model instances if they don't exist already.

When you create an application in using python manage.py startapp <app_name>, it creates an AppConfig class in apps.py file.

You can specify which signal to call in AppConfig class definition. Say the signal is called populate_models. In that case, modify AppConfig to look like following:

class AppConfig(AppConfig):
    name = 'app'

    def ready(self):
        from .signals import populate_models
        post_migrate.connect(populate_models, sender=self)

And in signals.py define the populate_models function.

def populate_models(sender, **kwargs):
    from django.contrib.auth.models import User
    from django.contrib.auth.models import group
    # create groups
    # assign permissions to groups
    # create users