Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Forms BooleanField on submit returns 'on'

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}

like image 392
Pooja Avatar asked Feb 14 '23 23:02

Pooja


1 Answers

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())
like image 112
Daniel Roseman Avatar answered Feb 23 '23 09:02

Daniel Roseman