Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic URL with variable django template

I'm trying to build a dynamic list of urls, based on a list of pages.

In my urls.py, the whole application is behind the namespace base:

urlpatterns = patterns('',
    url(r'^(?P<pk>[\w]+)/title/$', TitleSection.as_view(), name='title'),
    url(r'^(?P<pk>[\w]+)/amount/$', AmountSection.as_view(), name='amount'),
    url(r'^(?P<pk>[\w]+)/description/$', DescriptionSection.as_view(), name='description'), )

And in my context data I have the following list:

sections: ['title', 'amount', 'description']

I am trying to build the urls for each of the element in the sections.

I tried the following:

{% for section in sections %}
    <a href="{% url "base:"+section pk=object.id %}">..</a>
{% endfor %}

But I got the following error:

Could not parse the remainder: '+section' from '"base:"+section'

Then I tried:

<a href="{% url "base:{{section}}" pk=project.id %}">{{ section }}</a>

Error:

Reverse for '{{section}}' with arguments '()' and keyword arguments '{u'pk': 77}' not found. 0 pattern(s) tried: []

Do you know how to do this?

like image 582
nobe4 Avatar asked Apr 28 '16 10:04

nobe4


1 Answers

You can use the add template filter:

{% url "base:"|add:section pk=project.id %}
like image 162
Alasdair Avatar answered Nov 09 '22 07:11

Alasdair