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



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

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

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

完成此操作的最佳方法是什么?

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

此外,您还需要使用模型Group:https://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

最新更新