if语句中的Django表单字段失败

时间:2017-10-25 20:22:56

标签: python django

我使用if语句渲染Django表单来构造html模板:

{% for field in form %}
  {% if field.name == 'user_name' or 'phone' or 'email' or 'password1' %}
    <div class="col-12 col-md-6 col-lg-3">
      <p class="text-left m-0 fs-13">{{ field.label_tag }}</p>
      {% render_field field class="form-control is-invalid" %}
    </div>
  {% else %}
    bla bla
  {% endif %}
{% endfor %}

但是当我调用模板时,所有字段都是使用if语句代码构造的,但是我的字段如:location,birth_date ......在else语句中为True。

我做错了什么?

2 个答案:

答案 0 :(得分:0)

应该

{% if field.name == 'user_name' or 'phone' or 'email' or 'password1' %}

不是

{% if field.name in ['user_name', 'phone', 'email', 'password1'] %}

我会假设

or 'phone'

评估为真。

答案 1 :(得分:0)

在Python中你可以这样做:

if field.name in ['user_name', 'phone', 'email', 'password1']:

但是你不能在Django模板中定义一个列表,所以你必须做更详细的事情:

{% if field.name == 'user_name' or field.name == 'phone' or field.name == 'email' or field.name == 'password1' %}