Hello I am new to Django Forms. I am trying to add a checkbox in my form. When I submit the form I am expecting the checkbox field should return True or False, (depending on wheter or not the checkbox is checked).
But it is posting 'on' if the field is checked and posts nothing if the field is not checked. Following is code snippet from my form:
from django import forms
class MyForm(forms.Form):
def __init__(self):
self.fields['has_code']= forms.CharField(widget= forms.CheckboxInput())
What I want is when I post the form, I should get Post data as {'has_code': True}
That's your browser, not Django. But (though you don't show your view, which would have helped) you're looking in request.POST. Don't do that. The whole point of using a Django form is that it normalizes stuff like this, so you should look in the form's cleaned_data
dict.
def my_form_view(request):
if request.method == 'POST':
my_form = MyForm(request.POST)
if my_form.is_valid():
# my_form.cleaned_data['has_code'] is now a bool
You should also be using BooleanField
in the form. Plus, you shouldn't don't override __init__
unless you're doing something dynamic. Your form should just be:
class MyForm(forms.Form):
has_code = forms.BooleanField(widget= forms.CheckboxInput())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With