The Python Oracle

How to insert a checkbox in a django form

This video explains
How to insert a checkbox in a django form

--

Become part of the top 3% of the developers by applying to Toptal
https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Industries in Orbit Looping

--

Chapters
00:00 Question
00:26 Accepted answer (Score 76)
01:11 Answer 2 (Score 8)
01:33 Answer 3 (Score 4)
01:48 Thank you

--

Full question
https://stackoverflow.com/questions/6195...

Answer 1 links:
[https://docs.djangoproject.com/en/dev/re...]: https://docs.djangoproject.com/en/dev/re...
[https://docs.djangoproject.com/en/stable...]: https://docs.djangoproject.com/en/stable...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #django #djangoforms

#avk47



ACCEPTED ANSWER

Score 79


models.py:

class Settings(models.Model):
    receive_newsletter = models.BooleanField()
    # ...

forms.py:

class SettingsForm(forms.ModelForm):
    receive_newsletter = forms.BooleanField()

    class Meta:
        model = Settings

And if you want to automatically set receive_newsletter to True according to some criteria in your application, you account for that in the forms __init__:

class SettingsForm(forms.ModelForm):

    receive_newsletter = forms.BooleanField()

    def __init__(self):
        if check_something():
            self.fields['receive_newsletter'].initial  = True

    class Meta:
        model = Settings

The boolean form field uses a CheckboxInput widget by default.




ANSWER 2

Score 7


You use a CheckBoxInput widget on your form:

https://docs.djangoproject.com/en/dev/ref/forms/widgets/#django.forms.CheckboxInput

If you're directly using ModelForms, you just want to use a BooleanField in your model.

https://docs.djangoproject.com/en/stable/ref/models/fields/#booleanfield




ANSWER 3

Score 5


class PlanYourHouseForm(forms.ModelForm):

    class Meta:
        model = PlanYourHouse
        exclude = ['is_deleted'] 
        widgets = {
            'is_anything_required' : CheckboxInput(attrs={'class': 'required checkbox form-control'}),   
        }