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

我想创建两个组“驱动程序”和“管理员”。 每个组都应具有模型的引用权限。 “管理员”能够添加,删除和查看某些模型。 “驱动程序”仅能添加和查看某些模型。 做到这一点的最佳方法是什么?

评论
  • inisi
    inisi 回复

    It depends on the action in your project that leads to create these groups. I can guess, you want to create these groups once when you deploy your project without the need to enter the admin panel and create the groups manually. If so, I would recommend you to try RunPython migration for it: https://docs.djangoproject.com/en/3.0/ref/migration-operations/#django.db.migrations.operations.RunPython

    Also you will need to work with the model 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