Object ownership validation in Django UpdateView

后端 未结 2 1663
长情又很酷
长情又很酷 2021-02-11 03:02

EDIT:

The better solution for me was just using a permissions system, especially since I needed other types of controlled access to objects. I now use D

相关标签:
2条回答
  • 2021-02-11 03:19

    http://ccbv.co.uk/projects/Django/1.5/django.views.generic.edit/UpdateView/

    Go through the above link to understand how UpdateView works. get_object is supposed to return the model instance, It is not supposed to return HttpResponseRedirect object, that's why you are getting that error.

    Try doing the check in dispatch method like the following.

    def dispatch(self, request, *args, **kwargs):
        """ Making sure that only authors can update stories """
        obj = self.get_object()
        if obj.author != self.request.user:
            return redirect(obj)
        return super(UpdateStory, self).dispatch(request, *args, **kwargs)
    

    PS: I guess it is not recommended to override dispatch. But as you have to do the check on both get and post methods, overriding dispatch will be easier.

    0 讨论(0)
  • 2021-02-11 03:31

    The best approach would be to use another mixin, something like this:

    class AuthorRequiredMixin(object):
        def dispatch(self, request, *args, **kwargs):
            if self.object.author != self.request.user:
                return HttpResponseForbidden()
            return super(AuthorRequiredMixin, self).dispatch(request, *args, **kwargs)
    

    Of course you can return another HttpResponse, but keep in mind what is the proper use here.

    0 讨论(0)
提交回复
热议问题