[Fixed]-How to use the user_passes_test decorator in class based views?

30👍

Django 1.9 has authentication mixins for class based views. You can use the UserPassesTest mixin as follows.

from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin

class UserSettingsView(LoginRequiredMixin, UserPassesTestMixin, View):
    def test_func(self):
        return test_settings(self.request.user)

    def get_login_url(self):
        if not self.request.user.is_authenticated():
            return super(UserSettingsView, self).get_login_url()
        else:
            return '/accounts/usertype/'

Note that in this case you have to override get_login_url, because you want to redirect to a different url depending on whether the user is not logged in, or is logged in but fails the test.

For Django 1.8 and earlier, you should decorate the dispatch method, not get_initial.

@method_decorator(user_passes_test(test_settings, login_url='/accounts/usertype/')) 
def dispatch(self, *args, **kwargs):
    return super(UserSettingsView,  self).dispatch(*args, **kwargs)

Leave a comment