Redirect if already logged in through Django urls?

I use something like this in my urls.py:

from django.contrib.auth.views import login
from django.contrib.auth.decorators import user_passes_test


login_forbidden =  user_passes_test(lambda u: u.is_anonymous(), '/')

urlpatterns = patterns('',
    url(r'^accounts/login/$', login_forbidden(login), name="login"),

How about riding the Django login view?

Then add this little piece of code in that view:

if request.user.is_authenticated():
      # Redirect to profile

If you want to do something else in template itself for the register user:

{% if user.is_authenticated %}

Looking at the source code on Github, the default login view provided by django.contrib.auth will only use LOGIN_REDIRECT_URL if the login form is submitted via a POST request, and it has no next parameter. (The docs mention this too).

The login view doesn't actually do any checking of whether you're authenticated already or not - so an already-authenticated user hitting the page with a standard GET request will see the login form again - just the same as an unauthenticated user.

If you want different behaviour, I'd recommend writing your own login view.


I ended up writing a decorator for such task.

Please take note that I've made it quick & dirty.

from django.conf import settings
from django.shortcuts import redirect


def redirect_if_logged(f=None, redirect_to_url=None):
    u"""
    Decorator for views that checks that the user is already logged in, redirecting
    to certain URL if so.
    """
    def _decorator(view_func):
        def _wrapped_view(request, *args, **kwargs):
            if request.user.is_authenticated():
                redirect_url = redirect_to_url

                if redirect_to_url is None:
                    # URL has 'next' param?
                    redirect_url_1 = request.GET.get('next')
                    # If not, redirect to referer
                    redirect_url_2 = request.META.get('HTTP_REFERER')
                    # If none, redirect to default redirect URL
                    redirect_url_3 = settings.LOGIN_REDIRECT_URL

                    redirect_url = redirect_url_1 or redirect_url_2 or redirect_url_3

                return redirect(redirect_url, *args, **kwargs)
            else:
                return view_func(request, *args, **kwargs)
        return _wrapped_view

    if f is None:
        return _decorator
    else:
        return _decorator(f)

Tags:

Django