S Mev
S Mev

Reputation: 327

django {% url %} template looping

my url.py

app_name="application_name"
urlpatterns=[
    url(r"^staff/",include('application_name.staff_url', namespace='staff')),
    url(r"^customer/",include('application_name.customer_url', namespace='customer')),
]

staff_url.py

from application_name import views
app_name="staff"
urlpatterns=[
    url(r"^customers/",views.customers, name='customers'),
    url(r"^orders/$", views.orders, name='orders'),
    url(r"^payments/$", views.payments, name='payments'),
]

customer_url.py

from application_name import views
app_name="customer"
urlpatterns=[
    url(r"^items/",views.items, name='items'),
    url(r"^checkout/$", views.checkout, name='checkout'),
    url(r"^make_payment/$", views.make_payment, name='make_payment'),
]

staf url would be staff/orders or staff/payments customer urls would be customer/items or customer/checkout etc

In my view file I have put every link inside a list which would be iterated inside the template and placed it inside a session

This is my view.py

staffLink=[
    {'linkfield':"customers", 'name':"Customers",'slug':"staff"},
    {'linkfield':"orders", 'name':"Orders",'slug':"staff"},
    {'linkfield':"payments", 'name':"payments",'slug':"staff"}]
                    
links=staffLink
request.session['links']= links
request.session['sub']= 'staff'

context_dict = {'links':links} 
                

This is my html template

{% for link in request.session.links %}
    {% if request.session.sub =="staff" %}
        <a href="{% url  'application_name:staff' link.linkfield as the_url %}" class="nav-link">
    {% elif request.session.sub =="customer" %}
        <a href="{% url  'application_name:customer' link.linkfield as the_url %}" class="nav-link">
    {% endif %}
{% endfor %}

Pl

This are the following result

  1. When I include the if statement i.e. {% if request.session.sub =="staff" %}. The following error is produced

    django.template.exceptions.TemplateSyntaxError: Could not parse the remainder: '=="staff"' from '=="staff"'

  2. When I exclude the if statement so making it just <a href="{% url 'application_name:staff' link.linkfield as the_url %}" class="nav-link"> I did this for testing purposes. I get the following error

    django.urls.exceptions.NoReverseMatch: Reverse for 'staff' not found. 'staff' is not a valid view function or pattern name.

Please what am I to do to get the if statement working alongside the anchor statement

Upvotes: 1

Views: 43

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476813

You should write a space between the == and the "staff" string, so:

{% if request.session.sub == "staff" %}
    …
{% endif %}

as for the URL, you not refer to a URL which is an include(…) since that is a collection of URLs. For example:

<a href="{% url 'staff:customers' link.linkfield as the_url %}" class="nav-link">

Upvotes: 1

Related Questions