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

48 投票
3 回答
139641 浏览
提问于 2025-04-16 18:43

我有一个设置页面,用户可以选择是否想要接收新闻通讯。

我想要一个复选框来实现这个功能,并且希望如果数据库中'newsletter'的值为真,Django能够自动选中这个复选框。我该如何在Django中实现呢?

3 个回答

3
class PlanYourHouseForm(forms.ModelForm):

    class Meta:
        model = PlanYourHouse
        exclude = ['is_deleted'] 
        widgets = {
            'is_anything_required' : CheckboxInput(attrs={'class': 'required checkbox form-control'}),   
        }

当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。

7

你在表单上使用了一个复选框控件:

https://docs.djangoproject.com/en/dev/ref/forms/widgets/#django.forms.CheckboxInput

如果你直接使用模型表单(ModelForms),那么在你的模型里只需要用一个布尔字段(BooleanField)。

https://docs.djangoproject.com/en/stable/ref/models/fields/#booleanfield

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

如果你想根据应用中的某些条件自动将 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 这个小工具。

撰写回答