2015-11-04 62 views
0

我在做一个待办事项应用程序,我有一个表格是其中一个字段是一个选择字段都可以3 item_importance之间进行选择(重要,普通不重要)如何访问django模板中的forloop中的If语句中的元组值?

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

model.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" ] 

模板: 在这里,如果说法是错误的,我想访问取决于颜色的元组的值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 %} 

回答

0

的问题是,item_importancestr型的,而你对一个名字,这是不确定的比较吧。另外,您需要查看当前循环迭代的item对象上的属性item_importance

你应该做

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

非常感谢!它完美的工作! – quintocossio