Reputation: 4862
I finished reading the documentation for the reverse()
method of the Django URL dispatcher.
When is it useful?
Thank you!
Upvotes: 1
Views: 4643
Reputation: 13328
The function supports the dry principle - ensuring that you don't hard code urls throughout your app. A url should be defined in one place, and only one place - your url conf. After that you're really just referencing that info.
Use reverse()
to give you the url of a page, given either the path to the view, or the page_name
parameter from your url conf. You would use it in cases where it doesn't make sense to do it in the template with {% url 'my-page' %}
.
There are lots of possible places you might use this functionality. One place I've found I use it is when redirecting users in a view (often after the successful processing of a form)-
return HttpResponseRedirect(reverse('thanks-we-got-your-form-page'))
You might also use it when writing template tags.
Another time I used reverse()
was with model inheritance. I had a ListView
on a parent model, but wanted to get from any one of those parent objects to the DetailView
of it's associated child object. I attached a get__child_url()
function to the parent which identified the existence of a child and returned the url of it's DetailView
using reverse()
.
Upvotes: 6
Reputation: 627
The reverse() function is used in django to achieve DRY compliant urls in your views. Find a clearer explanation here
Upvotes: 3
Reputation: 798884
It's used when you want to resolve a view by name along with arguments to a URL in code. It's the backend for the {% url %}
template tag.
Upvotes: 2