如何在Django的项目设置过程中创建组并分配权限? [英] How to create groups and assign permission during project setup in django?

查看:148
本文介绍了如何在Django的项目设置过程中创建组并分配权限?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我可以在Django项目的管理区域中创建用户组并为其分配权限。我还可以通过从Django的身份验证模块导入 Group Permission 模型来创建组并为其分配权限。

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.

我想知道在设置项目时是否可以通过任何方式创建组并为其分配权限。因此,如果我有用户类型,则为管理员开发人员测试人员项目经理。他们基本上是具有不同权限级别的用户组。我没有自定义 User 模型,只能区分他们所分配的组。那么有没有一种方法可以创建这些组并为其分配所需的权限,例如当我运行 python manage.py migration 时为管理员创建权限时?

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?

推荐答案

您可以定义 post_migrate 信号创建所需的 User Group 模型实例(如果尚不存在)。

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

使用 python manage.py startapp< app_name> 创建应用程序时,它会创建<$ apps.py文件中的c $ c> AppConfig 类。

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

您可以在 AppConfig <中指定要调用的信号/ code>类定义。假设信号称为 populate_models 。在这种情况下,将AppConfig修改为如下所示:

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)

然后在signal.py中定义 populate_models 函数。

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

这篇关于如何在Django的项目设置过程中创建组并分配权限?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆