如何解决如何以Django形式插入复选框
| 我有一个设置页面,用户可以在其中选择是否要接收新闻通讯。 我需要一个复选框,如果数据库中的'newsletter \'为true,我希望Django选择它。如何在Django中实现?解决方法
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/zh_CN/dev/ref/forms/widgets/#django.forms.CheckboxInput
如果您直接使用ModelForms,则只想在模型中使用BooleanField。
https://docs.djangoproject.com/zh-CN/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
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。