Answer the question
In order to leave comments, you need to log in
How to "convert types" and fix strange if work in Jinja?
Faced with the strangeness of the Jinja template engine in Django. You need to set selected for the rendered dropdown option . I do it like this:
<select name="ft">
<option value="0">Все ({{ total_item }} шт.)</option>{% for i in menu_typ %}
<option value="{{ i.id }}"{% if request.GET.ft == i.id %} selected{% endif %}>
{{ i.szName|capfirst }} ({{ i.Num }} шт.)
</option>{% endfor %}
</select>
{% if request.GET.ft == i.id %}
does not work in principle. All sorts of experiments have shown that the cause of the type mismatch is: i.id -- number; request.GET.ft -- string. It was possible to bring both variables to the same type using the crutch add -- {% if request.GET.ft|add:0 == i.id|add:0 %}
. Thus, if you do this:<select name="ft">
<option value="0">Все ({{ total_item }} шт.)</option>{% for i in menu_typ %}
<option value="{{ i.id }}"{% if request.GET.ft|add:0 == i.id %} selected{% endif %}>
{{ i.szName|capfirst }} ({{ i.Num }} шт.)
</option>{% endfor %}
</select>
Answer the question
In order to leave comments, you need to log in
It’s not easier in the same place as menu_typ, to process the whole thing and return a list of some kind like this:
[{'object': object, 'selected': 'selected'}, {...}, {...}]
# html
{% for item in menu_typ %}
<option value="{{ item.object.id }}" {{ item.selected }}>
{{ item.object.szName|capfirst }} ({{ item.object.Num }} шт.)
</option>
{% endfor %}
или [(object, 'selected'), {object, ''), (...)]
{% for item, selected in menu_typ %}
<option value="{{ item.id }}" {{ selected }}>
{{ item.szName|capfirst }} ({{ item.Num }} шт.)
</option>
{% endfor %}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question