【问题标题】:Django form selected option not recognized, failed if statementDjango 表单选择的选项无法识别,if 语句失败
【发布时间】:2016-06-04 18:05:55
【问题描述】:

我有一个选择字段,即使出现错误(例如,必填字段为空),它也应保持其选定值,但它与当前值不匹配。

<label for="{{ form.movie.id_for_label }}" class="col-sm-3 control-label">Movie:</label>
<select id="{{ form.movie.id_for_label }}" name="movie" class="form-control">
{% for x,y in form.fields.movie.choices %}
    <option value="{{ x }}"{% if form.movie.value == x %} selected="selected"{% endif %}>{{ y }}</option>
{% endfor %}

如果我选择值 2,那么在发生错误后 form.movi​​e.value 的值是 2,但是在你的循环中的代码中,当 x = 2 时,等式不会返回 true,所以没有选择值将被保留。

为什么会这样,问题出在哪里?

【问题讨论】:

    标签: python django django-forms django-templates


    【解决方案1】:

    问题在于 form.fields.movi​​e.choices 将 id 作为数字返回(我猜是整数),而 中的数据form.movi​​e.value 是一个字符串,因此要比较两者,需要将 x 转换为字符串,如下所示: x|stringformat:"s",然后两者比较就没有问题了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-05
      • 2020-02-15
      • 1970-01-01
      • 2018-05-06
      • 1970-01-01
      • 2018-05-23
      相关资源
      最近更新 更多