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.
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')
- [Django]-How to understand lazy function in Django utils functional module
- [Django]-ImportError: bad magic number in 'time': b'\x03\xf3\r\n' in Django
- [Django]-Django : How can I find a list of models that the ORM knows?
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'))
👤AKX
- [Django]-Django models avoid duplicates
- [Django]-Django model with 2 foreign keys from the same table
- [Django]-Django filter JSONField list of dicts
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
- [Django]-The right place to keep my signals.py file in a Django project
- [Django]-How do I make an auto increment integer field in Django?
- [Django]-Remove duplicates in a Django query
Source:stackexchange.com