[Django]-How can I centralize URLs in Django templates?

6👍

Assuming your urls.py had an entry like this:

url(r'^course/(?P<course_id>\d+)/$', view_course, name='view_course')

You could have used the url template tag in your template:

<a href="{% url view_course course.id %}">Advanced Basketweaving</a>

Then when your client asked you to change the urls, you would have to make only one change in your urls.py.

url(r'^class/(?P<course_id>\d+)/$', view_course, name='view_course')

No change would be required in the templates.

Happy search and replacing — now you know for next time 😉

2👍

I believe the standard approach would be to use the url template tag:

{% url path.to.course_view 63 %}

…the main benefit being that you don’t need to hardcode URLs. So it’s a bit late now, but you might as well use the url tag this time around, just in case the client comes back tomorrow and wants them all to read /classes/class/63 – at which point you’ll only need to change the single URL pattern in your URLconf file.

1👍

Use sed (after committing to your version control). One search and replace over your whole directory.

Here’s a howto: http://www.grymoire.com/Unix/Sed.html

You should probably also create a view which redirects the old-style urls to the new-style urls, in case of any bookmarks, or any links you missed.

👤Marcin

Leave a comment