Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - How to pass several arguments to the url template tag

Tags:

In my urls.py I have:

(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/section/(?P<slug>[-\w]+)/$', 
    'paper.views.issue_section_detail', 
    {}, 
    'paper_issue_section_detail'
),

and I'm trying to do this in a template:

{% url paper_issue_section_detail issue.pub_date.year,issue.pub_date.month,issue.pub_date.day,section_li.slug %}

but I get this error:

TemplateSyntaxError
Caught an exception while rendering: Reverse for 'paper_issue_section_detail' with arguments '(2010, 1, 22, u'business')' and keyword arguments '{}' not found.

However, if I change the URL pattern to only require a single argument it works fine. ie:

(r'^(?P<year>\d{4})/$', 
    'paper.views.issue_section_detail', 
    {}, 
    'paper_issue_section_detail'
),

and:

{% url paper_issue_section_detail issue.pub_date.year %}

So it seems to complain when I pass more than a single argument using the 'url' template tag - I get the same error with two arguments. Is there a different way to pass several arguments? I've tried passing in named keyword arguments and that generates a similar error.

For what it's worth, the related view starts like this:

def issue_section_detail(request, year, month, day, slug):

How do I pass more than a single argument to the url template tag?

like image 738
Phil Gyford Avatar asked Jan 22 '10 18:01

Phil Gyford


People also ask

How do I pass parameters via URL in Django?

Django URL pass parameter to view You can pass a URL parameter from the URL to a view using a path converter. Then “products” will be the URL endpoint. A path converter defines which type of data will a parameter store. You can compare path converters with data types.

What is a more efficient way to pass variables from template to view in Django?

POST form (your current approach)

What does {% %} mean in Django?

{% %} and {{ }} are part of Django templating language. They are used to pass the variables from views to template. {% %} is basically used when you have an expression and are called tags while {{ }} is used to simply access the variable.

What does the built in Django template tag URL do?

The URL template tag is a typical type of Tag in the Django Template Language framework. This tag is specifically used to add View URLs in the Template Files.


1 Answers

I had the same issue (I'm using Django 1.3.1) and tried Gregor Müllegger's suggestion, but that didn't work for two reasons:

  • there should be no commas between year, month and day values
  • my class-based generic view seems to take only keyword arguments

Thus the only working solution was:

{% url news_detail slug=object.slug year=object.date|date:"Y" month=object.date|date:"m" day=object.date|date:"d" %}
like image 96
Vlad T. Avatar answered Oct 07 '22 05:10

Vlad T.