以django形式显示布尔模型字段作为单选按钮而不是默认的复选框

Lak*_*sad 11 django validation django-forms

这就是我的方法,在表单中显示一个布尔模型字段作为单选按钮是和否.

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
Run Code Online (Sandbox Code Playgroud)

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

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

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

Dan*_*man 15

使用TypedChoiceField.

class EmailEditForm(forms.ModelForm):
    to_send_form = forms.TypedChoiceField(
                         choices=choices, widget=forms.RadioSelect, coerce=int
                    )
Run Code Online (Sandbox Code Playgroud)


mpe*_*pen 6

field = BooleanField(widget=RadioSelect(choices=YES_OR_NO), required=False)


YES_OR_NO = (
    (True, 'Yes'),
    (False, 'No')
)
Run Code Online (Sandbox Code Playgroud)

  • 我认为丹尼尔的解决方案更好......我不认为这个会将提交的价值强制回到布尔. (2认同)