【发布时间】:2011-09-05 22:17:50
【问题描述】:
我有一个设置页面,用户可以在其中选择是否要接收时事通讯。
我想要一个复选框,如果 'newsletter' 在数据库中为真,我希望 Django 选择它。如何在 Django 中实现?
【问题讨论】:
标签: python django django-forms
我有一个设置页面,用户可以在其中选择是否要接收时事通讯。
我想要一个复选框,如果 'newsletter' 在数据库中为真,我希望 Django 选择它。如何在 Django 中实现?
【问题讨论】:
标签: python django django-forms
models.py:
class Settings(models.Model):
receive_newsletter = models.BooleanField()
# ...
forms.py:
class SettingsForm(forms.ModelForm):
receive_newsletter = forms.BooleanField()
class Meta:
model = Settings
如果您想根据应用程序中的某些条件自动将receive_newsletter 设置为True,您可以在__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
默认,布尔表单字段使用CheckboxInput 小部件。
【讨论】:
您在表单上使用 CheckBoxInput 小部件:
https://docs.djangoproject.com/en/dev/ref/forms/widgets/#django.forms.CheckboxInput
如果您直接使用 ModelForms,您只想在模型中使用 BooleanField。
https://docs.djangoproject.com/en/stable/ref/models/fields/#booleanfield
【讨论】:
class PlanYourHouseForm(forms.ModelForm):
class Meta:
model = PlanYourHouse
exclude = ['is_deleted']
widgets = {
'is_anything_required' : CheckboxInput(attrs={'class': 'required checkbox form-control'}),
}
【讨论】:
您可以在 forms.BooleanField() 参数上添加 required=False。
【讨论】: