【发布时间】:2017-12-12 13:50:08
【问题描述】:
我正在寻找一个带有复选框的 Django 表单。无论我选中或取消选中该框的天气如何,在 POST 请求中都没有检测到它。这是模板的代码-
<form action="annotate_page" method="post">{% csrf_token %}
<input id="repeat" type="checkbox" >
<label for="repeat">Repeat Sentence?</label>
<br>
<button type="submit">Next</button><br>
</form>
这是我的forms.py-
from django import forms
class AnnotateForm(forms.Form):
repeat=forms.BooleanField(required=False)
这是我的观点逻辑-
if request.method=="POST":
form = AnnotateForm(request.POST)
if form.is_valid():
print(request.POST)#prints only csrf_token in Query_dict
print(form.cleaned_data["repeat"])#Always false
不管复选框是否被选中,打印语句总是给出 False。
我知道有类似的问题,但它们并没有解决我的问题。
【问题讨论】:
-
在表单定义中,复选框被命名为
repeat。但是在您的 html 模板中,复选框根本没有名称! (id 是repeat,但这不是一回事。) -
为什么还要在 html 中硬编码表单字段?使用
{{ form.as_p }},Django 将为您绘制表单。