【问题标题】:How to access to tuple values in a If Statement inside a forloop in django templates?如何在 django 模板的 forloop 中访问 If 语句中的元组值?
【发布时间】:2016-02-04 08:55:43
【问题描述】:

我正在做一个待办事项应用程序,我有一个表单,其中一个字段是一个选择字段,您可以在 3 个 item_importance(重要、正常和不太重要)之间进行选择

在模板中,我想根据项目的重要性更改标签的颜色。问题是我想访问模板中的元组值,但我不知道如何。

模型.py:

item_importance = (
                  ('Important', 'Important'),
                  ('Normal', 'Normal'),
                  ('Less Important', 'Less Important')
                   )
class Item(models.Model):
     ...code...
     item_importance = models.CharField(max_length=25, choices=item_importance)

Form.py:

 class CreateItemForm(forms.ModelForm):
     description = forms.CharField(widget=forms.Textarea(attrs={'rows': 3, 'cols': 85}), max_length=200)
     deadline_date = forms.DateField(widget=forms.TextInput(attrs=   {'type': 'date'}))
 class Meta:
    model = Item
    fields = ["title", "description","item_importance", "deadline_date" ]

模板: 这里 if 语句是错误的,我想根据 de 标签的颜色访问元组的值。

{% for item in queryset %}
...code...
        <div class="panel-body">
            <div class="row">
                <div class="col-md-6">
                    <textarea class="form-control" rows="4" style="background-color:white; resize: none" readonly>{{ item.description }}</textarea>
                </div>
                <div class="col-md-6">

                {% if item_importance == Important %} #How do I access the value 'Important' of the tuple here? 
                    Importancia: <span class="label label-danger"> {{ item.item_importance }}</span>
                {% elif item_importance == Normal %} ##How do I access the value 'Normal' of the tuple here? 
                    Importancia: <span class="label label-warning"> {{ item.item_importance }}</span>
                {% else %}
                    Importancia: <span class="label label-success"> {{ item.item_importance }}</span>
                {% endif %}
                    {% endfor %}
                    <p> Deadline: <strong>{{ item.deadline_date }}</strong> ({{ item.deadline_date|timeuntil }})</p>

                </div>

            </div>
        </div>
    </div>
 </div>
</div>{% endfor %}   

【问题讨论】:

    标签: python django templates if-statement django-templates


    【解决方案1】:

    问题是item_importance 的类型是str,而您将它与未定义的名称进行比较。另外,您需要在当前循环迭代的item 对象上查找属性item_importance

    你应该这样做

    {% if item.item_importance == 'Important' %}
    ...
    {% elif item.item_importance == 'Normal' %}
    ...
    {% else %}
    ...
    {% endif %}
    

    【讨论】:

      猜你喜欢
      • 2021-08-11
      • 1970-01-01
      • 2014-07-01
      • 1970-01-01
      • 2016-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-26
      相关资源
      最近更新 更多