gpt4 book ai didi

python - 如何在 Django 表单中插入复选框

转载 作者:IT老高 更新时间:2023-10-28 22:03:09 28 4
gpt4 key购买 nike

我有一个设置页面,用户可以在其中选择是否要接收时事通讯。

我想要一个复选框,如果 '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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com