Django仅允许用户进入自己的个人资料以访问多个页面

时间:2018-08-27 14:36:26

标签: django

我有此URL私人/个人资料/ ,并且我写了类似这样的内容,以将除个人资料所有者以外的任何用户拒之门外

if int(pk) != profile:
            return HttpResponse("ERROR:...")
        else:
            return render(...)

问题是我有多个URL,例如“ private / profile / pk / editProfile”,我需要为每个URL编写上面的代码。

对此有更好的做法吗?

1 个答案:

答案 0 :(得分:0)

解决方案

from django.contrib.auth.mixins import AccessMixin

class OwnerOnlyMixin(AccessMixin):
    # you can override this method to handle what you want to do when user is not allowed.
    def handle_no_permission(self):
        return super().handle_no_permission()

    def dispatch(self, request, *args, **kwargs):
        if int(pk) != profile:
            return self.handle_no_permission()
        return super().dispatch(request, *args, **kwargs)

# example view class
class ProfileView(OwnerOnlyMixin, <... rest of your classes ...>):
    # config for the mixin, if you dont override the method `handle_no_permission`.
    raise_exception = False
    permission_denied_message = '' # if `raise_exception` is True, an exception with this message will be raised
    login_url = reverse('url-name') # if `raise_exception` is False, enter URL you want the user to redirect to

    # rest of your methods

您需要创建一个自定义的mixin类,该类将执行过滤非所有者的常见任务。
您可以看到我使用AccessMixin作为父类,可以选择不使用它。