Django Tip - Don't use hard coded urls in templates

Django, the Python based web framework has a template system which allows you to separate business logic from presentation. It provides a method of substituting variables inside the template using the {% var %} syntax.

One of the things you will often need to do is provide links to various views inside your application. However, the worst possible way to do this is to hard code pages inside your template. Developers of the Django framework are proponents of the DRY philosophy. This is evident in the URL mapping mechanism.

When you need to link to other views in your application, open your urls.py file. Copy the full package.app.view.view_name to your view. Then, inside your template in an anchor tag insert the following.


Link location

Django will then substitute the view name with the proper link relative to where your application lives.

The obvious advantage to doing this is if you ever publish your Django application to a different location you don’t have to update your links.