[Django]-How to check if, elif, else conditions at the same time in django template

22👍

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.

👤ohid

1👍

From what I understand, you want to associate each entry to a url depending on the category it belongs among the 3 categories. you can have this refactored in your Entry model in order to minimize logic in templates like:

class Entry(models.Model):
    category = ...

    def get_entry_url(self):
        if self.category == 'General Member':
            return reverse for the url 'member:person-list'

        elif self.category == 'Executive Committee Member':
            return reverse for the url 'member:execomember-list'

        else:
            return reverse for the url 'member:person-list'

Then in template:

{% for entry in entries %}
     <a href="{{ entry.get_entry_url }}"><li>{{ entry.category }}</li></a>
{% empty %}
    <li>No recent entries</li>
{% endfor %}

Leave a comment