django 用户权限和 Permission Required Mixin
django User permissions and Permission Required Mixin
在这段代码中,Django 将检查元组 permission_required 中的所有权限,以及是否拥有所有权限的用户可以访问视图。如果用户在给定列表或元组中具有任何权限,我想提供视图。例如:在这种特殊情况下,如果用户只有 polls.can_open 权限,我想提供视图
from django.contrib.auth.mixins import PermissionRequiredMixin
class MyView(PermissionRequiredMixin, View)
permission_required = ('polls.can_open', 'polls.can_edit')
mixin 默认不支持 OR 条件,但您可以简单地覆盖 has_permission()
方法来自己进行权限检查。类似于:
def has_permission(self):
user = self.request.user
return user.has_perm('polls.can_open') or user.has_perm('polls.can_edit')
MultiplePermissionsRequiredMixin in django-braces就是你所需要的。
文档是 here。演示:
from django.views.generic import TemplateView
from braces import views
class SomeProtectedView(views.LoginRequiredMixin,
views.MultiplePermissionsRequiredMixin,
TemplateView):
#required
permissions = {
"all": ("blog.add_post", "blog.change_post"),
"any": ("blog.delete_post", "user.change_user")
}
This view mixin can handle multiple permissions by setting the mandatory permissions attribute as a dict with the keys any and/or all to a list or tuple of permissions. The all key requires the request.user to have all of the specified permissions. The any key requires the request.user to have at least one of the specified permissions.
在这段代码中,Django 将检查元组 permission_required 中的所有权限,以及是否拥有所有权限的用户可以访问视图。如果用户在给定列表或元组中具有任何权限,我想提供视图。例如:在这种特殊情况下,如果用户只有 polls.can_open 权限,我想提供视图
from django.contrib.auth.mixins import PermissionRequiredMixin
class MyView(PermissionRequiredMixin, View)
permission_required = ('polls.can_open', 'polls.can_edit')
mixin 默认不支持 OR 条件,但您可以简单地覆盖 has_permission()
方法来自己进行权限检查。类似于:
def has_permission(self):
user = self.request.user
return user.has_perm('polls.can_open') or user.has_perm('polls.can_edit')
MultiplePermissionsRequiredMixin in django-braces就是你所需要的。
文档是 here。演示:
from django.views.generic import TemplateView
from braces import views
class SomeProtectedView(views.LoginRequiredMixin,
views.MultiplePermissionsRequiredMixin,
TemplateView):
#required
permissions = {
"all": ("blog.add_post", "blog.change_post"),
"any": ("blog.delete_post", "user.change_user")
}
This view mixin can handle multiple permissions by setting the mandatory permissions attribute as a dict with the keys any and/or all to a list or tuple of permissions. The all key requires the request.user to have all of the specified permissions. The any key requires the request.user to have at least one of the specified permissions.