Morten Engelsmann
Morten Engelsmann

Reputation: 213

Django template tag if doesn't compare as expected

Django version: $ python -m django --version: 3.1.2

My template contains this form:

        <form method="post">
        {% for samtalepartner in elev %}
            <input type="radio" 
                   name="elev" 
                   id="elev{{ forloop.counter  }}" 
                   value="{{ samtalepartner.id }}">
            <label for="elev{{ forloop.counter  }}">
                {{ samtalepartner.id }}{{ request.POST.elev }} 
                {% if samtalepartner.id == request.POST.elev %}
                <b>{{ samtalepartner.fulde_navn }}</b>
                {% else %}
                {{ samtalepartner.fulde_navn }}
                {% endif %}
            </label>
            <br>
        {% endfor %}
        <input type="submit" value="Fremhæv valgte">
        </form>

When I submit first time the browser shows:

1 Andersine Andersen
2 Sida Dida 

When selecting #2 and submitting again, I expected, as 2==2:

12 Andersine Andersen
22 <b>Sida Dida </b>

However, browser shows:

12 Andersine Andersen
22 Sida Dida 

How come that the two values do not compare and executes the {% if %} statement (rather than the {% else %}?

Upvotes: 2

Views: 280

Answers (1)

neverwalkaloner
neverwalkaloner

Reputation: 47374

Probably the problem is that request.POST.elev is a string and samtalepartner.id is an int. So try to convert it to string:

{% if samtalepartner.id|slugify == request.POST.elev %}

Upvotes: 2

Related Questions