我的模特中有这个:
class Task(Record):
class Status(models.IntegerChoices):
OPEN = 1, "Open"
COMPLETED = 2, "Completed"
status = models.IntegerField(choices=Status.choices, db_index=True, default=1)
然后,在我的模板中,我想显示所有状态,所以我在views.py中执行此操作:
context = {
"statuses": Task.Status.choices,
}
并且在我的模板中,它循环遍历:
{% for label,name in statuses %}
{{ label }}: {{ name }}
{% endfor %}
这导致:
1: Open
2: Completed
到目前为止,很好。但是现在,如果我使用GET参数,那么我将无法正常工作。假设我打开?id = 2,然后运行:
{% for label,name in statuses %}
{{ label }}: {{ name }}
{% if label == request.GET.id %}
YES
{% else %}
Sorry, not equal to {{ request.GET.id }}
{% endif %}
{% endfor %}
然后,我希望第一项显示是。但事实并非如此!以某种方式可以得出:
1: Open Sorry, not equal to 1
2: Completed Sorry, not equal to 1
我不明白为什么第一项没有评估为真。
像这样从请求中获取数据
request.GET.get('id')
并确保两者的数据类型必须相同,否则您将始终执行else条件。