I finished reading the documentation for the reverse() method of the Django URL dispatcher.
When is it useful?
Thank you!
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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 thepage_nameparameter 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)-
You might also use it when writing template tags.
Another time I used
reverse()was with model inheritance. I had aListViewon a parent model, but wanted to get from any one of those parent objects to theDetailViewof it’s associated child object. I attached aget__child_url()function to the parent which identified the existence of a child and returned the url of it’sDetailViewusingreverse().