Search code examples
djangodjango-views

Is there any order for inheriting PermissionRequiredMixin in Django?


I encountered this problem while following the Django tutorial 8.

I can redirect to the login page when I put PermissionRequiredMixin class first:

class AuthorCreate(PermissionRequiredMixin, CreateView):
    model = Author
    fields = '__all__'
    initial = {'date_of_death': '05/01/2018', }
    permission_required = 'catalog.add_author'

result of First

But when I put it in second position it doesn't work and goes directly to the page where the permission doesn't allow it:

class AuthorCreate(CreateView, PermissionRequiredMixin):

result of Second

I want to know is whether I should always put the PermissionRequiredMixin class at the first position. And how about LoginRequiredMixin? or what if I inherit both?


Solution

  • Yes, and this is documented for the LoginRequiredMixin mixin:

    This mixin should be at the leftmost position in the inheritance list.

    It is not explicitly stated for PermissionRequiredMixin but it works the same way.

    You should not need to inherit from both, as a user can't have the required permissions without logging in first, so PermissionRequiredMixin should be sufficient. If you really want to have both, LoginRequiredMixin should be the leftmost one.