【问题标题】:show selected option when render posted form in django在 django 中呈现发布的表单时显示选定的选项
【发布时间】:2018-09-20 10:02:36
【问题描述】:

我尝试使用如下所示的 ChoiceField 呈现表单:

<div class="col-25">
  <label for="category">Subcategory</label>
 </div>
 <div class="col-75">
  <select name="category" id="id_category">
    {% for x in FilterbyCategory.fields.category.choices %}
	    <option value="{{ x.0 }}"{% if FilterbyCategory.fields.category.value == x.0 %}selected{% endif %}> 
      {{ x.1 }}
    </option>
    {% endfor %}
  </select>
  </div>

当我提交表单时,我没有选择初始选项。 我这里有问题吗?

在视图函数中,我使用request.POST来创建一个实例:

filterbycategory = FilterbyCategory(request.POST)

然后我打印表单实例,我得到了这个:

     <tr><th><label for="id_category">Category:</label></th><td>
<select name="category" id="id_category">
      <option value="">---------</option>
      <option value="1" selected>BMW</option>
</select></td></tr>

但是手动渲染的模板中没有选择该选项。

【问题讨论】:

  • 检查selected是否正在模板中呈现(通过查看html)并尝试在其中放置一个空格。此时它将呈现为&lt;option value="1"selected&gt;

标签: html django forms django-forms


【解决方案1】:

我找到了解决方案。我必须直接获取字段值并像下面这样使用安全:

<option value="{{ x.0 }}"{% if FilterbyCategory.category.value|safe == x.0|safe %} selected{% endif %}> {{ x.1 }} </option>

它现在就像一个魅力。

【讨论】:

    猜你喜欢
    • 2011-04-16
    • 1970-01-01
    • 1970-01-01
    • 2011-06-23
    • 2012-05-01
    • 1970-01-01
    • 2022-01-05
    • 1970-01-01
    • 2019-12-06
    相关资源
    最近更新 更多