13

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?

1
  • Try to remove "" from href such as: <a href={% url "base:"+section pk=object.id %}>..</a> Commented Apr 28, 2016 at 10:33

3 Answers 3

20

You can use the add template filter:

{% url "base:"|add:section pk=project.id %}
Sign up to request clarification or add additional context in comments.

Comments

7

for my case that also worked

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

where url pattern is

url=[
path('base/<pk>/',base,name='base'),
]

Comments

3

Each of my models has a list view, a create/update view, and a delete view. These will be used by different functions within the customer's organisation to maintain the data they are responsible for. Each list view has links to the relevant create, update, and delete views. I wanted to build a page with a list of links to the list view. Here's how I did it.

I created a function based view in views.py.

def index(request):
     app     = request.resolver_match.app_name
     models  = apps.get_app_config(app).get_models()
     names   = [model._meta.model.__name__ for model in models]
     context = {
         "names" : names,
     }
     return render(request, app + '/index.html', context)

I created a template app/templates/app/index.html

{% for name in names %}
<li><a href="{% url request.resolver_match.app_name|add:':'|add:name|lower|add:'-review'%}">{{ name}}</a></li>                                              
{% endfor %}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.