python / beginner
Snippet
URL Reversal with reverse()
The reverse() function allows you to obtain a URL path from its name, keeping your code decoupled from hardcoded paths.
snippet.py
1
2
3
4
5
6
7
from django.urls import reversefrom django.http import HttpResponseRedirectdef my_view(request):# Redirect to a URL named 'home' in urls.pyurl = reverse('home')return HttpResponseRedirect(url)
django
Breakdown
1
reverse('home')
Looks up the URL pattern named 'home' and returns the actual string path.