ohid ohid - 2 months ago 5
Python Question

How to check if, elif, else conditions at the same time in django template

I have 3 category in category field. I want to check it in django template and assign appropirte urls for 3 distinct category.

I tried:

{% for entry in entries %}
{% if entry.category == 1 %}
<a href="{% url 'member:person-list' %}"><li>{{ entry.category }}</li></a>
{% elif entry.category == 2 %}
<a href="{% url 'member:execomember-list' %}"><li>{{ entry.category}}</li></a>
{% else %}
<a href="{% url 'member:lifemember-list' %}"><li>{{ entry.category}}</li></a>
{% endif %}
{% empty %}
<li>No recent entries</li>
{% endfor %}


But I know python only check first matching condition with if. Therefore it gave only one desired result. How do I get all three entries with their correct links?

Edit:

Though python only check first matching if condition, when use elif within for loop it check each condition until endfor loop. Therefore my answer below worked fine.

Answer

This is my working answers:

   {% for entry in entries %}
        {% if entry.category == 'General Member' %}
        <a href="{% url 'member:person-list' %}"><li>{{ entry.category }}</li></a>
    {% elif entry.category == 'Executive Committee Member' %}
        <a href="{% url 'member:execomember-list' %}"><li>{{ entry.category}}</li></a>
    {% else %}
    <a href="{% url 'member:person-list' %}"><li>{{ entry.category}}</li></a>
        {% endif %}
    {% empty %}
        <li>No recent entries</li>
  {% endfor %}

Webpage view of output:

enter image description here

For more clarifications, I check my code with the django shell. See the snippet of my shell:

enter image description here

Even I change the order of if conditions, result remain the same. See my shell code with output:

enter image description here

Do you see any wrong with my codes? Its fully comply with the python conditions and gives expected results. Anybody can check it on their django shell.