【问题标题】:Blank option in required ChoiceField必填选项字段中的空白选项
【发布时间】:2011-07-14 10:53:32
【问题描述】:

我希望 ModelForm 中的 ChoiceField 有一个空白选项 (-----),但这是必需的。

我需要有空白选项以防止用户意外跳过该字段,从而选择错误的选项。

【问题讨论】:

    标签: django django-forms


    【解决方案1】:

    您还可以覆盖表单的__init__() 方法并修改choices 字段属性,重新签名一个新的元组列表。 (这可能对动态变化有用):

    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        self.fields['my_field'].choices = [('', '---------')] + self.fields['my_field'].choices
    

    【讨论】:

      【解决方案2】:

      这至少适用于 1.4 及更高版本:

      CHOICES = (
          ('', '-----------'),
          ('foo', 'Foo')
      )
      
      class FooForm(forms.Form):
          foo = forms.ChoiceField(choices=CHOICES)
      

      Since ChoiceField is required (by default), it will complain about being empty when first choice is selected and wouldn't if second.

      这样做比 Yuji Tomita 展示的方式更好,因为这样你就可以使用 Django 的本地化验证消息。

      【讨论】:

      • 这是个好主意,它避免了编写一些自定义验证器。
      【解决方案3】:

      您可以使用clean_FOO 验证该字段

      CHOICES = (
          ('------------','-----------'), # first field is invalid.
          ('Foo', 'Foo')
      )
      class FooForm(forms.Form):
          foo = forms.ChoiceField(choices=CHOICES)
      
          def clean_foo(self):
              data = self.cleaned_data.get('foo')
              if data == self.fields['foo'].choices[0][0]:
                  raise forms.ValidationError('This field is required')
              return data
      

      如果是 ModelChoiceField,您可以提供 empty_label 参数。

      foo = forms.ModelChoiceField(queryset=Foo.objects.all(), 
                          empty_label="-------------")
      

      这将保持所需的表单,如果选择-----,将引发验证错误。

      【讨论】:

        【解决方案4】:

        在参数中添加 null = True

        喜欢这个

        gender = models.CharField(max_length=1, null = True)
        

        http://docs.djangoproject.com/en/dev/ref/models/fields/


        您的意见

        THEME_CHOICES = (
            ('--', '-----'),
            ('DR', 'Domain_registery'),
        )
            theme = models.CharField(max_length=2, choices=THEME_CHOICES)
        

        【讨论】:

        • 不是可选字段吗?我希望它是必需的,但没有默认值。
        • THEME_CHOICES = ( ('--', '-----), ('DR', 'Domain_registery'), ) 主题 = models.CharField(max_length=2,choices=THEME_CHOICES)
        猜你喜欢
        • 2015-12-10
        • 2023-03-17
        • 1970-01-01
        • 1970-01-01
        • 2016-06-12
        • 2013-06-11
        • 1970-01-01
        • 2013-04-20
        • 2015-11-13
        相关资源
        最近更新 更多