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?
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 .
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.
Use named urls and the {% url %}
tag.
urlpatterns = [
#...
url(r'^articles/$', views.archive, name='news-archive'),
#...
]
{% url 'news-archive' %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With