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?
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/ .
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 .
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.
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.
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.
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With