首页 > 解决方案 > 如何在 Django 管理员中以编程方式创建具有模型权限的组?

问题描述

我想创建两个组“驱动程序”和“管理员”。每个组都应具有模型的尊重权限。

管理员”能够添加、删除和查看某些模型。

驱动程序”能够添加和查看某些模型。

完成这项工作的最佳方法是什么?

标签: pythondjangopython-3.xdjango-modelsdjango-admin

解决方案


这取决于您的项目中导致创建这些组的操作。我可以猜到,您希望在部署项目时创建这些组一次,而无需进入管理面板并手动创建组。如果是这样,我建议您尝试RunPython迁移:https ://docs.djangoproject.com/en/3.0/ref/migration-operations/#django.db.migrations.operations.RunPython

您还需要使用该模型Grouphttps ://docs.djangoproject.com/en/3.0/ref/contrib/auth/

迁移的一个简单示例如下所示:

from django.db import migrations


def forwards_func(apps, schema_editor):
    Group = apps.get_model("django.contrib.auth", "Group")
    # Create the groups you need here...


def reverse_func(apps, schema_editor):
    Group = apps.get_model("django.contrib.auth", "Group")
    # Delete the groups you need here...


class Migration(migrations.Migration):

    dependencies = []

    operations = [
        migrations.RunPython(forwards_func, reverse_func),
    ]

可以通过以下命令创建新的空迁移:

python manage.py makemigrations myapp --empty

推荐阅读