【问题标题】:Display a boolean model field in a django form as a radio button rather than the default Checkbox将 django 表单中的布尔模型字段显示为单选按钮而不是默认复选框
【发布时间】:2010-11-05 05:32:26
【问题描述】:

这就是我的做法,将表单中的布尔模型字段显示为单选按钮是和否。

choices = ( (1,'Yes'),
            (0,'No'),
          )

class EmailEditForm(forms.ModelForm):

    #Display radio buttons instead of checkboxes
    to_send_form = forms.ChoiceField(choices=choices,widget=forms.RadioSelect)

    class Meta:
    model = EmailParticipant
    fields = ('to_send_email','to_send_form')

    def clean(self):
    """
    A workaround as the cleaned_data seems to contain u'1' and u'0'. There may be a better way.
    """

    self.cleaned_data['to_send_form'] = int(self.cleaned_data['to_send_form'])
    return self.cleaned_data

正如您在上面的代码中看到的,我需要一个干净的方法将输入字符串转换为整数,这可能是不必要的。

有没有更好和/或 djangoic 的方式来做到这一点。如果有,怎么做?

不,使用BooleanField 似乎会导致更多问题。使用它对我来说似乎很明显;但事实并非如此。为什么会这样。

【问题讨论】:

    标签: django django-forms validation


    【解决方案1】:

    使用TypedChoiceField

    class EmailEditForm(forms.ModelForm):
        to_send_form = forms.TypedChoiceField(
                             choices=choices, widget=forms.RadioSelect, coerce=int
                        )
    

    【讨论】:

    【解决方案2】:
    field = BooleanField(widget=RadioSelect(choices=YES_OR_NO), required=False)
    
    
    YES_OR_NO = (
        (True, 'Yes'),
        (False, 'No')
    )
    

    【讨论】:

    • 我认为 Daniel 的解决方案更好....我认为这不会将提交的值强制转换回布尔值。
    • 这个答案没有说明它是否应该放在模型中或表单中。我对 django 表单有点陌生,我想看看这是否可行以及它在哪里可行?
    • @StevenRogers 这是一个表单字段而不是模型字段;所以它代表 django 表单中的一个字段,其中多个字段组成一个表单。另一方面,模型字段表示数据库表的列。
    【解决方案3】:

    如果你想要水平渲染器,请使用它。

    http://djangosnippets.org/snippets/1956/

    【讨论】:

      【解决方案4】:

      如果您想处理布尔值而不是整数值,那么这就是这样做的方法。

      forms.TypedChoiceField(
          choices=((True, 'Yes'), (False, 'No')),
          widget=forms.RadioSelect,
          coerce=lambda x: x == 'True'
      )
      

      【讨论】:

        猜你喜欢
        • 2017-10-22
        • 1970-01-01
        • 2021-10-05
        • 2017-01-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多