使用 request.GET 和选择的 Django 模板中的比较未正确评估
Comparison in Django template using request.GET and choices is not properly evaluated
我的模型中有这个:
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 条件。
Capturing url parameters in request.GET
我的模型中有这个:
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 条件。
Capturing url parameters in request.GET