【问题标题】:How to insert a checkbox in a django form如何在 Django 表单中插入复选框
【发布时间】:2011-09-05 22:17:50
【问题描述】:

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

我想要一个复选框,如果 'newsletter' 在数据库中为真,我希望 Django 选择它。如何在 Django 中实现?

【问题讨论】:

    标签: python django django-forms


    【解决方案1】:

    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 小部件。

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 这总体上是一个更好的答案。编写和使用 django 的内置对象的代码更少。
      【解决方案3】:
      class PlanYourHouseForm(forms.ModelForm):
      
          class Meta:
              model = PlanYourHouse
              exclude = ['is_deleted'] 
              widgets = {
                  'is_anything_required' : CheckboxInput(attrs={'class': 'required checkbox form-control'}),   
              }
      

      【讨论】:

        【解决方案4】:

        您可以在 forms.BooleanField() 参数上添加 required=False

        【讨论】:

        • 这不会填充任何内容。
        猜你喜欢
        • 2012-01-08
        • 1970-01-01
        • 1970-01-01
        • 2011-06-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多