reverse()
| Django documentation
Let's suppose that in your urls.py
you have defined this:
url(r'^foo$', some_view, name='url_name'),
In a template you can then refer to this url as:
<!-- django <= 1.4 -->
<a href="{% url url_name %}">link which calls some_view</a>
<!-- django >= 1.5 or with {% load url from future %} in your template -->
<a href="{% url 'url_name' %}">link which calls some_view</a>
This will be rendered as:
<a href="/foo/">link which calls some_view</a>
Now say you want to do something similar in your views.py
- e.g. you are handling some other URL (not /foo/
) in some other view (not some_view
) and you want to redirect the user to /foo/
(often the case on successful form submission).
You could just do:
return HttpResponseRedirect('/foo/')
But what if you want to change the URL in the future? You'd have to update your urls.py
and all references to it in your code. This violates the DRY (Don't Repeat Yourself) principle and the whole idea of editing in one place only - which is something to strive for.
Instead, you can say:
from django.urls import reverse
return HttpResponseRedirect(reverse('url_name'))
This looks through all URLs defined in your project for the URL defined with the name url_name
and returns the actual URL /foo/
.
This means that you refer to the URL only by its name
attribute - if you want to change the URL itself or the view it refers to you can do this by editing one place only - urls.py
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…