Django: Redirect logged in users from login page

Viewed 58413

I want to set up my site so that if a user hits the /login page and they are already logged in, it will redirect them to the homepage. If they are not logged in then it will display normally. How can I do this since the login code is built into Django?

10 Answers

I'm assuming you're currently using the built-in login view, with

(r'^accounts/login/$', 'django.contrib.auth.views.login'),

or something similar in your urls.

You can write your own login view that wraps the default one. It will check if the user is already logged in (through is_authenticated attribute official documentation) and redirect if he is, and use the default view otherwise.

something like:

from django.contrib.auth.views import login

def custom_login(request):
    if request.user.is_authenticated:
        return HttpResponseRedirect(...)
    else:
        return login(request)

and of course change your urls accordingly:

(r'^accounts/login/$', custom_login),

For Django 2.x, in your urls.py:

from django.contrib.auth import views as auth_views
from django.urls import path

urlpatterns = [
    path('login/', auth_views.LoginView.as_view(redirect_authenticated_user=True), name='login'),
]

Since class based views (CBVs) is on the rise. This approach will help you redirect to another url when accessing view for non authenticated users only.

In my example the sign-up page overriding the dispatch() method.

class Signup(CreateView):
    template_name = 'sign-up.html'

    def dispatch(self, *args, **kwargs):
        if self.request.user.is_authenticated:
            return redirect('path/to/desired/url')
        return super().dispatch(*args, **kwargs)

Cheers!

All you have to do is set the "root" url to the homepage view. Since the homepage view is already restricted for logged on users, it'll automatically redirect anonymous users to the login page.

Kepp the url as it is. And add something like:

(r'^$', 'my_project.my_app.views.homepage'),
Related