Fred Collins
Fred Collins

Reputation: 5010

How to insert a checkbox in a django form

I've a settings page where users can select if they want to receive a newsletter or not.

I want a checkbox for this, and I want that Django select it if 'newsletter' is true in database. How can I implement in Django?

Upvotes: 48

Views: 144258

Answers (3)

Timmy O'Mahony
Timmy O'Mahony

Reputation: 53971

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.

Upvotes: 79

Paul McMillan
Paul McMillan

Reputation: 20107

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

Upvotes: 7

Mahadev
Mahadev

Reputation: 51

class PlanYourHouseForm(forms.ModelForm):

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

Upvotes: 5

Related Questions