Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a variable to {% url %} tag in django?

I have 2 views: a and b they all render to one template T. There are also a_2 and b_2 views. And T template should generate urls to the a_2 and b_2 views.

however I cannot use {% url %} because I cannot pass url name as a parametr.

I cannot generate the whole url in views because i should do it multiple times (one on a row in a table - so it could be hundreeds of links)

I do not want to write 2 exactly the same template. So the question is - how to avoid this ?

like image 473
Korniltsev Anatoly Avatar asked Dec 12 '22 19:12

Korniltsev Anatoly


1 Answers

This is fixed in django 1.5.

In versions prior to 1.5 you need to use

{% extends 'base.html' %}

{% load url from future %}

{% url 'name_as_a_string' %}
{% url name_stored_in_variable %}

From https://docs.djangoproject.com/en/dev/releases/1.5/

One deprecated feature worth noting is the shift to “new-style” url tag. Prior to Django 1.3, syntax like {% url myview %} was interpreted incorrectly (Django considered "myview" to be a literal name of a view, not a template variable named myview). Django 1.3 and above introduced the {% load url from future %} syntax to bring in the corrected behavior where myview was seen as a variable.

like image 91
Ted Avatar answered Dec 25 '22 19:12

Ted