简体   繁体   English

Django模板中的表单字段值

[英]Form field value in django template

Quick question, 快速提问

I am able to output the value of a form field using 我可以使用以下形式输出表单字段的值

{{ form.field.value }}

But I cannot seem to check that value in an if statement. 但是我似乎无法在if语句中检查该值。

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

Always fails.. any ideas? 总是失败..有什么想法吗?

The field is a boolean type field. 该字段是布尔类型字段。

EDIT - the answer given below works for some fields.. Here is what i'm trying to do; 编辑-下面给出的答案适用于某些领域。这是我想要做的;

Form field is a boolen field in a model, using this code in the form; 表单字段是模型中的布尔字段,使用表单中的此代码;

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

The output is correct (eg. True or False) when using {{form.information_request.value}} - but when I use it in an IF statement in the template - it never works.. 使用{{form.information_request.value}}时,输出是正确的(例如,True或False)-但是,当我在模板的IF语句中使用输出时,它永远不会工作。

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

The {% if %} tag evaluates a variable, and if that variable is "true" (ie exists, is not empty, and is not a false boolean value) the contents of the block are output: {% if %}标签对一个变量求值,并且如果该变量为“ true”(即存在,不为空并且不是假布尔值),则输出块的内容:

Eg: 例如:

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

To test for falsiness: 要测试虚假性:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM