post

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.

<a href="{% url package.app.view.view_name %}">
Link location
</a>

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.

[tags]Django,tutorial[/tags]

About Joe

Director of Product working @AWeber. Discuss and RT about social media, product development and mobile platforms. Opinions are my own (you can't have 'em).

  • Hi! Quick question that’s totally off topic. Do you know how to make your site mobile friendly?My site
    loooks weird when viewing from my iphone 4. I’m trying to
    find a theme or plugin that might bbe ablke too correct tyis
    problem. If you have any recommendations, please share.
    Appreciate it!

  • Pingback: kings chance online casino()

  • Pingback: commeny blanchir ses dents()