0

每个项目都有一个下拉列表,可以选择并保存它。重新加载页面后,我希望用户能够看到他们所做的选择。

楷模:

CATEGORY_CHOICES = (
    ('0', 'All Position'),
    ('1', 'Green'),
    ('2', 'Aqua'),
    ('3', 'Blue'),
    ('4', 'Yellow'),
)

class ColorCoat(models.Model):
    title = models.CharField(max_length=100)
    category = models.CharField(max_length=1, choices=CATEGORY_CHOICES)

    def get_category(self):
        return CATEGORY_CHOICES[int(self.category)][1]

我尝试了什么:

{% for item in color_items %}
...
    {% if item.category == 1 or 3 %}
        <span>Greenish Blue</span>
    {% endif %}
    {% if item.category == 2 or 4 %}
         <span>Turquoise</span>
    {% endif %}
{% endfor %}

如何正确检查 item.category 的值是什么?

4

1 回答 1

1

您的逻辑有缺陷,请使用:

{% if item.category == '1' or item.category == '3' %}

和:

{% if item.category == '2' or item.category == '4' %}

该表达式item.category == 2 or 4并不意味着您认为它会做什么;它被解释为(item.category == 2) or 4。如果item.category确实是2,则该表达式的计算结果为(True) or 4,但如果item.category3,则(False) or 4返回4,这True在布尔上下文中被考虑。

此外,您在 中有字符串item.category但您正在针对int值进行测试。

于 2013-04-15T18:48:49.673 回答