python - 如何在 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
推荐阅读
- apache-spark - hdp 沙盒/zeppelin 上的 %spark2.r 不起作用
- javascript - 编写高级正则表达式
- android-studio - 如何使用 Android Studio 为 Flutter 库创建 .jar 文件
- r - 排列Grob中的垂直对齐和高度
- c++ - 单独输入线程上的 OpenGL 无效操作错误
- ubuntu-16.04 - 在 Ubuntu 16.04 上正确启动和停止 pgAdmin4
- javascript - 将代码直接放入弹窗函数中
- javascript - 来自文件的 Javascript 导入类产生“Uncaught SyntaxError: Unexpected Identifier”
- android - Statelesswidget,带firebase实时数据库的statefulwidget
- c# - 为来宾用户从 Azure Active Directory 获取访问令牌时出现异常