Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify URLs in Django templates?

Question is: What's the right way of writing URL in Django templates?

If I write them explicitly (like this):

some_template.html

{% extends "base.html" %}
{% block someblock %}
    <a href="/some_url">Anchor</a>
{% endblock someblock %}

and then I decide to change my URL scheme I will have to change both - template and urls.py module (Seems this way conflicts with the DRY principles)

Another way is to use variables (like this):

some_template.html

{% extends "base.html" %}
{% block someblock %}
    <a href="{{ url_var }}">Anchor</a>
{% endblock someblock %}


views.py

def some_url (request):
    return HttpResponse('Hello, world!')

def another_url (request):
    return render_to_response('some_template.html', {'url_var': reverse('some_url')}

But in this case if I use template inheritance I have to specify in context ALL of the url variables (also for the parent templates). Probably it is not a good way too.

So what is the decision?

like image 458
Alexander Avatar asked May 05 '11 13:05

Alexander


People also ask

How do I name a URL in Django?

Django offers a way to name urls so it's easy to reference them in view methods and templates. The most basic technique to name Django urls is to add the name attribute to url definitions in urls.py .

How does Django define dynamic URL?

You can use named groups in the urls to pass data to views and it won't require any dynamic updating in the urls. The named part containing page. alias will be simply passed as a keyword argument to your view function. You can use it to get the actual Page object.


1 Answers

Use named urls and the {% url %} tag.

urlpatterns = [
    #...
    url(r'^articles/$', views.archive, name='news-archive'),
    #...
]
{% url 'news-archive' %}
like image 68
DrTyrsa Avatar answered Sep 24 '22 04:09

DrTyrsa