How to set True as default value for BooleanField on Django?

PythonDjangoDjango Models

Python Problem Overview


I am using BooleanField in Django.

By default, the checkbox generated by it is unchecked state. I want the state to be checked by default. How do I do that?

Python Solutions


Solution 1 - Python

If you're just using a vanilla form (not a ModelForm), you can set a Field initial value ( https://docs.djangoproject.com/en/2.2/ref/forms/fields/#django.forms.Field.initial ) like

class MyForm(forms.Form):
    my_field = forms.BooleanField(initial=True)

If you're using a ModelForm, you can set a default value on the model field ( https://docs.djangoproject.com/en/2.2/ref/models/fields/#default ), which will apply to the resulting ModelForm, like

class MyModel(models.Model):
    my_field = models.BooleanField(default=True)

Finally, if you want to dynamically choose at runtime whether or not your field will be selected by default, you can use the initial parameter to the form when you https://docs.djangoproject.com/en/2.2/ref/forms/api/#django.forms.Form.initial">initialize it:

form = MyForm(initial={'my_field':True})

Solution 2 - Python

from django.db import models

class Foo(models.Model):
    any_field = models.BooleanField(default=True)

Solution 3 - Python

I am using django==1.11. The answer get the most vote is actually wrong. Checking the document from django, it says:

> initial -- A value to use in this Field's initial display. This value is not used as a fallback if data isn't given.

And if you dig into the code of form validation process, you will find that, for each fields, form will call it's widget's value_from_datadict to get actual value, so this is the place where we can inject default value.

To do this for BooleanField, we can inherit from CheckboxInput, override default value_from_datadict and init function.

class CheckboxInput(forms.CheckboxInput):
    def __init__(self, default=False, *args, **kwargs):
        super(CheckboxInput, self).__init__(*args, **kwargs)
        self.default = default

    def value_from_datadict(self, data, files, name):
        if name not in data:
            return self.default
        return super(CheckboxInput, self).value_from_datadict(data, files, name)

Then use this widget when creating BooleanField.

class ExampleForm(forms.Form):
    bool_field = forms.BooleanField(widget=CheckboxInput(default=True), required=False)

Solution 4 - Python

In Django 3.0 the default value of a BooleanField in model.py is set like this:

class model_name(models.Model):
    example_name = models.BooleanField(default=False)

Solution 5 - Python

I found the cleanest way of doing it is this.

Tested on Django 3.1.5

class MyForm(forms.Form):
    my_boolean = forms.BooleanField(required=False, initial=True)

I found the answer here

Solution 6 - Python

Both initial and default properties were not working for me, if that's your case try this:

class MyForm(forms.ModelForm):
    validated = forms.BooleanField()

    class Meta:
        model = MyModel
        fields = '__all__'

    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)

        self.fields['validated'].widget.attrs['checked'] = True

Solution 7 - Python

Another way to check the default state in BooleanField is:

   active = forms.BooleanField(
    widget=forms.CheckboxInput(
        attrs={
            'checked': True
        }
    )
  )

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBin ChenView Question on Stackoverflow
Solution 1 - PythonMichael C. O'ConnorView Answer on Stackoverflow
Solution 2 - Pythonvaibhav sharmaView Answer on Stackoverflow
Solution 3 - PythonD.WView Answer on Stackoverflow
Solution 4 - PythonVicenteCView Answer on Stackoverflow
Solution 5 - PythonSajad JalilianView Answer on Stackoverflow
Solution 6 - PythonRicardo VilaçaView Answer on Stackoverflow
Solution 7 - PythonLeotrim LotaView Answer on Stackoverflow