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

Fre*_*ins 32 python django django-forms

我有一个设置页面,用户可以选择是否要收到简报.

我想要一个复选框,我希望Django选择它,如果'newsletter'在数据库中是真的.我怎样才能在Django中实现?

Tim*_*ony 54

models.py

class Settings(models.Model):
    receive_newsletter = models.BooleanField()
    # ...
Run Code Online (Sandbox Code Playgroud)

forms.py

class SettingsForm(forms.ModelForm):
    receive_newsletter = forms.BooleanField()

    class Meta:
        model = Settings
Run Code Online (Sandbox Code Playgroud)

如果您想根据应用程序中的某些条件自动将receive_newsletter设置为True,那么您可以在表单中考虑__init__

forms.py

class SettingsForm(forms.ModelForm):

    receive_newsletter = forms.BooleanField()

    def __init__(self):
        if check_something():
            self.fields['receive_newsletter'].initial  = True

    class Meta:
        model = Settings
Run Code Online (Sandbox Code Playgroud)

默认情况下,布尔表单字段使用CheckboxInput小部件.


Pau*_*lan 6

您在表单上使用 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