【发布时间】:2012-01-22 11:48:07
【问题描述】:
我有一个使用以下表单的应用程序:
class ConfirmForm(forms.Form):
account_name = forms.CharField(widget=forms.HiddenInput)
up_to_date = forms.BooleanField(initial=True)
我使用以下模板摘录中的表格:
<form class="confirmform" action="/foo/" enctype="multipart/form-data" method="post">
{{ confirm_form.up_to_date }} Check if this data brings the account up to date.<br>
{{ confirm_form.account_name }} <input type="submit" name="confirm" value="Confirm" />
</form>
我的观点使用以下基本代码结构:
if request.method == 'POST':
#check for 'confirm' because I actually have multiple forms in this page
if 'confirm' in request.POST:
confirm_form = ConfirmForm(request.POST)
if confirm_form.is_valid():
#do stuff
else:
c['confirm_form'] = confirm_form
else:
c['confirm_form'] = ConfirmForm({'account_name':'provided_value'})
有两点不对:
1) 即使我设置了 initial=True,但在页面加载时复选框未选中
2) 除非我选中复选框,否则表单始终无效。它仅针对 up_to_date 给出错误:“此字段是必需的。”
我已阅读this similar question,但他的解决方案不适用于我的项目。
那么……这是怎么回事?
编辑:
我更新了上面的代码以更忠实于我的实际代码。
问题 #1 是我的错,因为我在实例化表单时通过绑定数据覆盖了初始值。
问题 #2 我仍然在考虑一个问题。在up_to_date 上使用required=False 可以解决问题,但是使用默认小部件似乎不正确,BooleanField 可以是NULL(导致有效性检查失败)或True,但绝不是@ 987654330@.
【问题讨论】:
标签: django django-forms