如何在UpdateView django中获取request.user

时间:2017-12-15 13:22:42

标签: django django-views django-class-based-views

我想将updateview限制为specefic用户。我如何知道哪个用户请求了更新视图。我是django.Thanks的新手

1 个答案:

答案 0 :(得分:3)

您可以覆盖UpdateView的dispatch方法

class ExampleUpdate(UpdateView):

    model = Example
    form_class = ExampleUpdateForm
    template_name = 'path/to/example.html'

    def dispatch(self, request, *args, **kwargs):
        # here you can make your custom validation for any particular user
        if not request.user.is_superuser:
            raise PermissionDenied()
        return super().dispatch(request, *args, **kwargs)

或者您也可以使用PermissionRequiredMixin

from django.contrib.auth.mixins import PermissionRequiredMixin

class MyView(PermissionRequiredMixin, UpdateView):
    permission_required = 'aoo_name.can_update'

这个mixin就像permission_required装饰器一样,检查访问视图的用户是否具有所有权限。您应该使用permission_required参数

指定权限(或权限的可迭代)
  

要设置用户特定权限,您可以阅读:   https://docs.djangoproject.com/en/dev/topics/auth/default/#permissions-and-authorization