Execute code in dispatch method with LoginRequiredMixin

Question:

class HomeView(LoginRequiredMixin, TemplateView):
    template_name = 'home.html'

    # Variant 1
    def dispatch(self, request, *args, **kwargs):

        # Do some other checks after making sure the user is logged in
        # This does not work because the LoginRequiredMixin
        # will be executed after calling the super method

        return super().dispatch(self, request, *args, **kwargs)

    # Variant 2
    def dispatch(self, request, *args, **kwargs):
        response = super().dispatch(self, request, *args, **kwargs)

        # Do some other checks after making sure the user is logged in
        # This does not work because this part will be also executed
        # if the user is not logged in

        return response

How can I execute code in the dispatch method after the user is logged in using a Class Based View with the LoginRequiredMixin?

Asked By: Nepo Znat

||

Answers:

You should use the UserPassesTestMixin with a test_func() method containing your logic. You don’t need to override dispatch at all.

class HomeView(UserPassesTestMixin, TemplateView):
    ...
    def test_func(self):
        return self.request.user.is_authenticated and my_custom_logic(self.request.user)
Answered By: Daniel Roseman

A simple solution would be to use your second variant and then check if the user is authenticated yourself:

# Variant 2
def dispatch(self, request, *args, **kwargs):
    response = super().dispatch(self, request, *args, **kwargs)

    if request.user.is_authenticated:
        # Your code here

    return response

Note: You should not need to override the dispatch method to achieve that, but since it was your question.

Answered By: dethos

I’d use UserPassesTestMixin with a test_func() method containing the logic.

You can use the LoginRequiredMixin before UserPassesTestMixin.

from django.views.generic.base import TemplateView
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin

class HomeView(LoginRequiredMixin, UserPassesTestMixin, TemplateView):

    def test_func(self):
        try:
            # some logic
            return True
        except:
            return False

The order is relevant. It’ll check first if the user is authenticated, before considering the test_func(). More about it here.

Answered By: Tiago Martins Peres
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.