Skip to content

Redirecting an already logged in user in Django using Class Based Views

On my site I wanted visitors to the home page to be immediately redirected to the member’s area if they were already logged in.

This saves them a click or two and gets them straight down to business, as opposed to being forced to read my home page asking them to buy something they’ve already purchased.

In class based views (CBV) you need to access the dispatch method:

class HomeView(TemplateView):
    template_name = "website/home.html"

    def dispatch(self, request, *args, **kwargs):
        if request.user.is_authenticated:
            return redirect('members:members-home')
        return super(HomeView, self).dispatch(request, *args, **kwargs)

Firstly – you have to use the US spelling of “despatch” – but I guess no framework is perfect!

The class says “Right guys – lets go to the dispatch() method first. Ok – if the user is authenticated already then redirect to the the members home page route. Otherwise just display the template_name template”

Easy peasy!


Leave a Reply