如标题所述。 BooleanField 即使选中也不会返回 True。这个让我抓狂!
首先,我根据基于模型的字段 ID 列表检索复选框。
表单.py
class MyForm(forms.Form):
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
fields = Fields.objects.all()
for field in fields:
field_name = field.ID
self.fields[field_name] = forms.BooleanField(required=False, widget=forms.CheckboxInput(attrs={'class':'checkbox-small'}), label=field_name)
即使在 DOM 中选中,处理程序也永远不会返回 True。
模型.py
def myFormHandler(request):
siteDictionary = getDictionary(request)
if request.method == 'POST':
form = MyForm(request.POST, error_class=DivErrorList, auto_id='%s')
if form.is_valid():
fields = Fields.objects.all()
for field in fields:
if form.cleaned_data[field.ID]:
print "Finally returned true!"
else:
form = MyForm()
siteDictionary['form'] = form
return render_to_response('page.html', siteDictionary, context_instance=RequestContext(request))
有什么想法吗?感谢您的帮助。
编辑这是模板
<table cellspacing="0" cellpadding="0" border="0" class="table-all">
<thead>
<tr>
<th><input type="checkbox" name="check" class="checkall checkbox-small" /></th>
<th>Name</th>
</tr>
</thead>
<tbody>
{% for field in form %}
<tr>
<td>{{ field }}</td>
<td>{{ field.label }}</td>
</tr>
{% endfor %}
</tbody>
</table>
<div id="pager" class="pager">
<form method="post" action=".">{% csrf_token %}
<button type="submit" class="green"><span>Submit</span></button>
</form>
</div>
最佳答案
您的字段不在您的 HTML 表单元素内,因此未提交。
关于无论是否选中,Django BooleanField 都会返回 False(空),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8288606/