Skip to content Skip to sidebar Skip to footer

How To Use The User_passes_test Decorator In Class Based Views?

I am trying to check certain conditions before the user is allowed to see a particular user settings page. I am trying to achieve this using the user_passes_test decorator. The fun

Solution 1:

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

classUserSettingsView(LoginRequiredMixin, UserPassesTestMixin, View):
    deftest_func(self):
        return test_settings(self.request.user)

    defget_login_url(self):
        ifnot self.request.user.is_authenticated():
            returnsuper(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/')) defdispatch(self, *args, **kwargs):
    returnsuper(UserSettingsView,  self).dispatch(*args, **kwargs)

Post a Comment for "How To Use The User_passes_test Decorator In Class Based Views?"