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.
8👍
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
- [Django]-Redis Python – how to delete all keys according to a specific pattern In python, without python iterating
- [Django]-AngularJS with Django – Conflicting template tags
- [Django]-How can I get the object count for a model in Django's templates?
4👍
class PlanYourHouseForm(forms.ModelForm):
class Meta:
model = PlanYourHouse
exclude = ['is_deleted']
widgets = {
'is_anything_required' : CheckboxInput(attrs={'class': 'required checkbox form-control'}),
}
- [Django]-Django admin file upload with current model id
- [Django]-Error trying to install Postgres for python (psycopg2)
- [Django]-Using django-rest-interface
Source:stackexchange.com