Django and urls.py: How do I HttpResponseRedirect via a named url?


Question

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?

1
25
4/22/2014 2:50:33 PM

Accepted Answer

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.

42
5/8/2019 8:53:24 AM

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')

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon