225👍
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 initialize it:
form = MyForm(initial={'my_field':True})
149👍
from django.db import models
class Foo(models.Model):
any_field = models.BooleanField(default=True)
- [Django]-How to disable admin-style browsable interface of django-rest-framework?
- [Django]-What does "'tests' module incorrectly imported" mean?
- [Django]-How to pass information using an HTTP redirect (in Django)
12👍
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)
- [Django]-Is there a way to loop over two lists simultaneously in django?
- [Django]-How do I create a slug in Django?
- [Django]-Create empty queryset by default in django form fields
4👍
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)
- [Django]-Can we append to a {% block %} rather than overwrite?
- [Django]-How do I install psycopg2 for Python 3.x?
- [Django]-Django filter queryset __in for *every* item in list
3👍
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)
- [Django]-Django: Why do some model fields clash with each other?
- [Django]-How to change a django QueryDict to Python Dict?
- [Django]-Django 1.7 – makemigrations not detecting changes
1👍
Another way to check the default state in BooleanField is:
active = forms.BooleanField(
widget=forms.CheckboxInput(
attrs={
'checked': True
}
)
)
- [Django]-Strings won't be translated in Django using format function available in Python 2.7
- [Django]-Django – Rotating File Handler stuck when file is equal to maxBytes
- [Django]-Create empty queryset by default in django form fields
0👍
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
- [Django]-ImproperlyConfiguredError about app_name when using namespace in include()
- [Django]-Annotate with latest related object in Django
- [Django]-How to get superuser details in Django?
0👍
I tried to change inital of BooleanField:
def __init__(self, *args, **kwargs):
super(UserConfirmForm,self).__init__(*args, **kwargs)
self.fields['bool_field'].initial = True
but it didn’t work.
My solve:
def __init__(self, *args, **kwargs):
kwargs['initial'] = {'bool_field': True}
super(UserConfirmForm,self).__init__(*args, **kwargs)
It works like:
UserConfirmForm(initial={'bool_field':True})
but we can’t call form in Generic editing views.
I think this is a great alternative to a regular call form object.
- [Django]-How to use permission_required decorators on django class-based views
- [Django]-Change a form value before validation in Django form
- [Django]-Nginx doesn't serve static
0👍
If default=True
in models.BooleanField() below doesn’t work in models.py
:
# "models.py"
class MyModel(models.Model): # Here
state = models.BooleanField(default=True)
Then, use the following solutions below in admin.py
:
# "admin.py"
class MyModelForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
kwargs['initial'] = {'state': True}
super().__init__(*args, **kwargs)
@admin.register(MyModel)
class MyModelAdmin(admin.ModelAdmin):
form = MyModelForm
Or:
# "admin.py"
class MyModelForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['state'].widget.attrs['checked'] = True
@admin.register(MyModel)
class MyModelAdmin(admin.ModelAdmin):
form = MyModelForm
Or:
# "admin.py"
class MyModelForm(forms.ModelForm):
state = forms.BooleanField(initial=True, required=False)
@admin.register(MyModel)
class MyModelAdmin(admin.ModelAdmin):
form = MyModelForm
Or:
# "admin.py"
class MyModelForm(forms.ModelForm):
state = forms.BooleanField(
widget=forms.CheckboxInput(
attrs={
'checked': True
}
)
)
@admin.register(MyModel)
class MyModelAdmin(admin.ModelAdmin):
form = MyModelForm
Or:
class MyModelForm(forms.ModelForm):
class Meta:
widgets = {
'state': forms.CheckboxInput(attrs={'checked':True}),
}
@admin.register(MyModel)
class MyModelAdmin(admin.ModelAdmin):
form = MyModelForm
- [Django]-How to write setup.py to include a Git repository as a dependency
- [Django]-Sending an SMS to a Cellphone using Django
- [Django]-Using the reserved word "class" as field name in Django and Django REST Framework