0

Of its available methods, which is the ideal place to place permission checking? If get(), should it also be in the post()?

The code lives in its own permissions.py and looks like this:

def has_perm_or_is_owner(user_object,
                          permission,
                          instance=None):
    if instance is not None:
        if user_object == instance.user:
            return True
    return user_object.has_perm(
        permission
    )  

It checks whether the request.user is the rightful owner of the form instance. This particular form should not be viewable to anyone else.

The code I am trying to find a place to insert within the CBV, is here:

can_edit = has_perm_or_is_owner(
            self.request.user,
            'profile.fill_form',
            instance=obj,
        )
        if not can_edit:
            raise Http404

This is usually an easy choice with, say, an UpdateView, as I'll just stick it inside the get_object(). With FormViews, this is a bit more ambiguous. Thoughts?

edit: if you have comments pertaining to what the actual best practice would be in cases of CBV permissions, I would love to hear it.

Jay Jung
  • 1,805
  • 3
  • 23
  • 46
  • If you want to check the permission in both `get` and `post` method, you could do it in [`dispatch`](https://docs.djangoproject.com/en/1.11/ref/class-based-views/base/#django.views.generic.base.View.dispatch) method. – AKS Dec 27 '17 at 12:09
  • @AKS, I was looking into overriding the dispatch method as you suggested when I found a comment suggesting the use of the [UserPassesTestMixin](https://docs.djangoproject.com/en/1.11/topics/auth/default/#django.contrib.auth.mixins.UserPassesTestMixin). What do you think of this method? edit: the dispatch-related post I was looking at: https://stackoverflow.com/questions/27824181/django-a-class-based-view-with-mixins-and-dispatch-method – Jay Jung Dec 27 '17 at 12:51

0 Answers0