Reputation: 31
As stated in the title. BooleanField wont return True even if checked. This one is driving me nuts!
First I retrieve checkboxes based on a list of field id's based on a model.
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)
The handler never returns True even if checked on in the DOM.
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))
Any ideas? Thanks for your help.
EDIT Here is the template
<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>
Upvotes: 3
Views: 2279
Reputation: 600059
Your fields aren't inside your HTML form element, so aren't submitted.
Upvotes: 2
Reputation: 309109
Is field.ID
an integer? If so, you need to coerce it to a string when generating 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)
Upvotes: 0