【发布时间】:2015-12-20 07:44:23
【问题描述】:
我需要开始在我现有的基于 Django 的 Web 服务中使用模型级权限。我想添加的权限类型是 django admin 的默认值(“add”、“change”、“delete”)并且已经存在(我可以在 admin 中看到它们。)
我的数据库中已经有很多用户,所以手动分配权限是不可能的。
如何为我的应用中的模型子集为每个现有用户和未来用户自动分配这些权限?
【问题讨论】:
我需要开始在我现有的基于 Django 的 Web 服务中使用模型级权限。我想添加的权限类型是 django admin 的默认值(“add”、“change”、“delete”)并且已经存在(我可以在 admin 中看到它们。)
我的数据库中已经有很多用户,所以手动分配权限是不可能的。
如何为我的应用中的模型子集为每个现有用户和未来用户自动分配这些权限?
【问题讨论】:
您可以使用组来执行此操作,使用 get_or_create 方法,如下面的代码:
from django.contrib.auth.models import Group, Permission, User
from django.contrib.contenttypes.models import ContentType
content_type = ContentType.objects.get_for_model(User)
add_permission = Permission.objects.get(content_type=content_type,codename='add_user')
change_permission = Permission.objects.get(content_type=content_type,codename='change_user')
delete_permission = Permission.objects.get(content_type=content_type,codename='delete_user')
group, created = Group.objects.get_or_create(name='your_group')
if created: #assign permission to all users in database
group.permissions.add(add_permission, change_permission, delete_permission)
for user in User.objects.all():
user.groups.add(group)
这样,如果尚未创建组,则创建它,将数据库中的所有用户添加到其中并添加所需的权限。此外,对于您想要添加这些权限的每个新用户,您应该将其添加到组中,因此应该继续创建以下代码:
groupGroup.objects.get(name='your_group')
user.groups.add(group)
如需文档,请点击here
【讨论】: