在文档中,它说可以使用以下给定的方式来授予自定义权限。has_perm装饰器用于检查用户权限。但是,它并没有说明这些权限的定义位置或作用。我不需要定义它们吗?如果是,我在哪里以及如何做?感谢所有帮助。
class Task(models.Model):
...
class Meta:
permissions = (
("view_task", "Can see available tasks"),
("change_task_status", "Can change the status of tasks"),
("close_task", "Can remove a task by setting its status as closed"),
)
答案 0 :(得分:0)
您可以创建自定义权限类,我已经在下面完成了。
class BaseModelPerm(permissions.DjangoModelPermissions):
def get_custom_perms(self, method, view):
app_name = view.model._meta.app_label
if hasattr(view, 'extra_perms_map'):
return [app_name+"."+perms for perms in view.extra_perms_map.get(method, [])]
else:
return []
def has_permission(self, request, view):
perms = self.get_required_permissions(request.method, view.model)
perms.extend(self.get_custom_perms(request.method, view))
return (
request.user and
(request.user.is_authenticated() or not self.authenticated_users_only) and
request.user.has_perms(perms)
)
具有以上权限的用户可以在下面的任何视图中使用
class UserView(viewsets.ModelViewSet):
""" User model view for the admin user """
model = User
permission_classes = (
permissions.IsAuthenticated,
accounts_permissions.IsStaffOrVendor,
accounts_permissions.BaseModelPerm,
)
extra_perms_map = {
'GET': ["can_view_user"]
}
extra_perms_map是与该方法相关的权限指令。