Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 200
Akoi Meexx Avatar asked Jul 30 '09 19:07

Akoi Meexx


People also ask

How do I redirect in urls py Django?

Django Redirects: A Super Simple Example Just call redirect() with a URL in your view. It will return a HttpResponseRedirect class, which you then return from your view. Assuming this is the main urls.py of your Django project, the URL /redirect/ now redirects to /redirect-success/ .

How do I reference a URL in Django?

Django offers a way to name urls so it's easy to reference them in view methods and templates. The most basic technique to name Django urls is to add the name attribute to url definitions in urls.py .

How do I pass URL parameters in Django?

Django URL pass parameter to view You can pass a URL parameter from the URL to a view using a path converter. Then “products” will be the URL endpoint. A path converter defines which type of data will a parameter store. You can compare path converters with data types.

What is the difference between HttpResponseRedirect and redirect?

There is a difference between the two: In the case of HttpResponseRedirect the first argument can only be a url . redirect which will ultimately return a HttpResponseRedirect can accept a model , view , or url as it's "to" argument. So it is a little more flexible in what it can "redirect" to.


2 Answers

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.

like image 77
Soviut Avatar answered Sep 23 '22 07:09

Soviut


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') 
like image 40
Rob Grant Avatar answered Sep 25 '22 07:09

Rob Grant