mardi 5 mai 2015

Where to check for 403 in a Django CBV?

I am making a basic app to teach beginners. Each user can write notes, but I want to make it so that a user cannot view or update a different user's notes.

I have the following view, but I had to repeat myself.

from django.core.exceptions import PermissionDenied

...

class NoteUpdate(LoginRequiredMixin, UpdateView):

    ...

    def get(self, request, *args, **kwargs):
        self.object = self.get_object()

        if self.object.owner != self.request.user:
            raise PermissionDenied

        return super(NoteUpdate, self).get(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        self.object = self.get_object()

        if self.object.owner != self.request.user:
            raise PermissionDenied

        return super(NoteUpdate, self).post(request, *args, **kwargs)

I feel like there is probably a way to do this without repeating myself. Yeah, I could write a method like this and call it from both:

def check_permission(self):
   if self.object.owner != self.request.user:
        raise PermissionDenied 

But what I really mean is am I overriding the wrong methods? Is there a more traditional way to do this? It feels a little weird overriding .get() and .post()

Aucun commentaire:

Enregistrer un commentaire