pythondjangodjango-authenticationdjango-class-based-views

Authentication for class based views in Django


class AdminView(generic.ListView):
    model = get_user_model()
    fields = ['first_name', 'username', 'is_active']
    template_name = 'users/admin.html'

class AdminUpdateView(UpdateView):
    model = get_user_model()
    fields = ['is_active']
    template_name = 'users/user_update.html'
    success_url = reverse_lazy('users:admin')

There are two views in django which I have created and I want them to be accessed only when the admin/staff logins. How do I go about it?


Solution

  • You can use the UserPassesTestMixin [Django-doc] and LoginRequiredMixin [Django-doc] mixins, and specify as condition that the user should be an is_superuser. Since you need these twice, we can make first a composite mixin:

    from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
    
    class AdminStaffRequiredMixin(LoginRequiredMixin, UserPassesTestMixin):
        
        def test_func(self):
            return self.request.user.is_superuser or self.request.user.is_staff

    Next you can add the mixin to your class-based views:

    class AdminView(AdminStaffRequiredMixin, generic.ListView):
        model = get_user_model()
        fields = ['first_name', 'username', 'is_active']
        template_name = 'users/admin.html'
    
    class AdminUpdateView(AdminStaffRequiredMixin, UpdateView):
        model = get_user_model()
        fields = ['is_active']
        template_name = 'users/user_update.html'
        success_url = reverse_lazy('users:admin')