29

I'm writing a member-based web application, and I need to be able to redirect the page after login. I want to use the named url from my urls.py script in my views.py file for the login application, but I can't for the life of me figure out what to do. What I have is this:

def login(request): 
if request.session.has_key('user'):
    if request.session['user'] is not None:
        return HttpResponseRedirect('/path/to/page.html')

What I want to accomplish is something like:

def login(request): 
if request.session.has_key('user'):
    if request.session['user'] is not None:
        return HttpResponseRedirect url pageName

I get syntax errors when I execute this, any ideas?

4 Answers 4

48

You need to use the reverse() utils function.

from django.urls import reverse
# or Django < 2.0 : from django.core.urlresolvers import reverse

def myview(request):
    return HttpResponseRedirect(reverse('arch-summary', args=[1945]))

Where args satisfies all the arguments in your url's regular expression. You can also supply named args by passing a dictionary.

3
  • Awesome, thanks for the help! I must have just been searching through the django docs all wrong.
    – Akoi Meexx
    Jul 30, 2009 at 19:44
  • It's from django.urls import reverse these days. Aug 23, 2018 at 1:22
  • @partofthething I've updated the answer to include a commented out import
    – Soviut
    Aug 23, 2018 at 5:54
15

The right answer from Django 1.3 onwards, where the redirect method implicitly does a reverse call, is:

from django.shortcuts import redirect

def login(request):
    if request.session.get('user'):
        return redirect('named_url')
1
  • 3
    Also, if you are using a named app within your project, the syntax is redirect('appName:urlName')
    – medley56
    Mar 27, 2018 at 15:35
7

A more concise way to write that if statement would be if request.session.get('user'). has_key is deprecated nowadays, and .get() returns None (by default, changeable by passing a second parameter). So combining this with Soviut's reply:

from django.core.urlresolvers import reverse

def login(request): 
    if request.session.get('user'):
         return HttpResponseRedirect(reverse('my-named-url'))
3
from django.core.urlresolvers import reverse
from django.shortcuts import redirect

def login(request):
    if request.session.get('user'):
        return redirect(reverse('name-of-url'))

Also see https://docs.djangoproject.com/en/dev/topics/http/urls/#reverse-resolution-of-urls

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.