python - django 模板中的表单字段值

标签 python django

快速提问,

我可以使用

输出表单字段的值
{{ form.field.value }}

但我似乎无法在 if 语句中检查该值。

{% if form.field.value == 'whatever' %}

总是失败..有什么想法吗?

该字段为 bool 类型字段。

编辑 - 下面给出的答案适用于某些领域。这就是我正在尝试做的;

表单字段是模型中的 bool 字段,在表单中使用此代码;

self.fields['information_request'] = forms.TypedChoiceField(choices=((True, 'Yes'), (False, 'No')), widget=forms.RadioSelect, coerce=lambda x: x and (x.lower() != 'false'))

使用 {{form.information_request.value}} 时输出是正确的(例如 True 或 False)——但是当我在模板的 IF 语句中使用它时——它永远不会工作。

最佳答案

https://docs.djangoproject.com/en/1.3/ref/templates/builtins/#if

The {% if %} tag evaluates a variable, and if that variable is "true" (i.e. exists, is not empty, and is not a false boolean value) the contents of the block are output:

例如:

{% if form.field.value %}
    ...
{% endif %}

测试是否为假:

{% if not form.field.value %}
    ...
{% endif %}

关于python - django 模板中的表单字段值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9305011/

相关文章:

python - Django / python : raw sql with multiple tables

python - 如果是odoo9中的公共(public)类,继承哪个基类

Python-获取列表中少数类的百分比

python - pymongo - 消息长度大于服务器最大消息大小

python - Django 中 Multi-Tenancy 的最佳解决方案是什么?

android - 无法从 Android 模拟器连接到本地主机

python - 使用 python tqdm 库重定向 stdout 和 stderr

python - 计算从 hdf5 文件进行内存映射的大型 numpy 数组的平均值

python - HTTP 版本或 header 会影响网页的视觉外观吗?

Django:模型字段的元组/固定大小列表