Home > Software design >  Django use variable from template inside of urls.py
Django use variable from template inside of urls.py

Time:08-26

I need to create a menu, and item names/links in the menu needs to be generated dynamically. So I have the following code which is working and lists all the menu items.

views.py:

def idf1(request):

    return render(request, 'idfs/idf.html')

base.html:

{% extends 'base.html' %}

{% block idfs %}
{% for each in idf_list %}
    <li>
        <a href="/idfs/{{each}}">{{ each }}</a>
    </li>
{% endfor %}
{% endblock %}

urls.py

url(r'^idfs/{{each}}$', myapp.views.idf),

It looks very stupid. because I used {{each}} hoping that base.html variable is accessible in the urls.py

How can I use the variable inside of my urls.py? Is it even possible?

CodePudding user response:

(NB: I am assuming you are on an early version of django based on use of 'url' in urls.py rather than 'path')

Assuming idf_list isn't db objects, just a list of simple variables like, say, three digit integers, you could do something like this.

views.py:

#provide current idf via argument to view. Default is 111
def idf1(request, idf="111"):
    #pass current idf to template as idf_context
    context['idf_context'] = idf
    return render(request, 'idfs/idf.html', context)

base.html:

{% extends 'base.html' %}
{% load static %}

{% block idfs %}
<ul>
{% for each in idf_list %}
    <li>
        {% if each == idf_context %} -> <!-- comment: highlight the current idf -->{% endif %}
        <!-- use template url tag to generate URL -->
        <a href="{% url "idf-page" {{each}} %}" >{{each}}</a>
    </li>

{% endfor %}
</ul>
{% endblock %}

urls.py

#here we define the url as possessing a 3 digit idf value eg /idfs/111
url(r'^idfs/?P<idf>[0-9]{3})$', myapp.views.idf, name="idf-page"),
  • Related