如标题所述。即使选中,BooleanField也不会返回True。这个让我疯了!
首先,我根据模型的字段ID列表检索复选框。
forms.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。
models.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>
答案 0 :(得分:2)
您的字段不在HTML表单元素中,因此不会提交。
答案 1 :(得分:0)
field.ID
是整数吗?如果是这样,您需要在生成field_name
时将其强制转换为字符串。
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 = str(field.ID)
self.fields[field_name] = forms.BooleanField(required=False, widget=forms.CheckboxInput(attrs={'class':'checkbox-small'}), label=field_name)