我有一个设置页面,用户可以在其中选择是否要接收时事通讯。
我想要一个复选框,如果 'newsletter' 在数据库中为真,我希望 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
默认, bool 表单字段使用 CheckboxInput
小部件。
关于python - 如何在 Django 表单中插入复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6195424/