CheckboxInput Django form fields

Listen as audio

Hello Techies,

In this blog, we will check different CheckboxInput Django form fields(BooleanField) with examples.

The fields of the form are classes themselves; They manage form data and perform validation when a form is submitted.

Syntax : FieldType(**kwargs) 

Different types of CheckboxInput Django form fields

BooleanField

The default widget for this input is the CheckboxInput. The boolean field in Django form is a checkbox field that stores either True or False value. The empty value is False by default. It normalizes to a Python True or False value.

This field is used when we want to store values ​​like is_valid, is_admin, is_staff, is_active, is_student, etc.

Syntax: BooleanField(**kwargs)

Example:

class CheckBoxInputForm(forms.Form):
    is_valid = forms.BooleanField(label='Is Valid', label_suffix = " : ",
                                  required = True,  disabled = False,
                                  widget=forms.widgets.CheckboxInput(attrs={'class': 'checkbox-inline'}),
                                  help_text = "Please check the box as this field is required.",
                                  error_messages = {'required':"Please check the box"})

Let’s run the server and check the result.

Rendered HTML

CheckboxInput Django form fields(BooleanField)

Rendered HTML with validation

CheckboxInput Django form fields(BooleanField)

Explanation:

Field OptionsDescription
labelThe label argument allows you to specify a “Field Caption” label for this area.
label_suffixThe label_suffix argument allows you to insert some text after the field’s label.
requiredBy default, each field assumes a value as required, so you need to set required = false to make it not necessary.
widgetWidget Argument lets you specify widget classes to use when presenting this field. So you can use bootstrap class or other CSS class for this field to decorate your field. Also, you can pass the choice list.
For eg. is_valid= forms.BooleanField(widget=forms.widgets.CheckboxInput(attrs={‘class’: ‘checkbox-inline’}))
error_messageserror_messages argument allows you to overwrite the default error message that the field will raise. Pass the error message you want to overwrite in the dictionary with matching keys.
disabledDisabled Boolean Argument, when set to true, disables the form field using the disabled HTML attribute so that it cannot be edited by users.

I hope you understand all the CheckboxInput Django form fields. For more details, you can check out the official site.

Find the source code for CheckboxInput Django form fields Github link at:

https://github.com/pranalikambli/django_form_fields

thank you

Leave a Comment