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

前端 未结 2 911
梦如初夏
梦如初夏 2020-12-31 20:29

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

2条回答
  •  执笔经年
    2020-12-31 20:46

    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 , 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:

    from django.apps import AppConfig
    from django.db.models.signals import post_migrate
    
    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
    

提交回复
热议问题