Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将django表单中的布尔模型字段显示为单选按钮,而不是默认复选框_Django_Django Forms_Validation - Fatal编程技术网

将django表单中的布尔模型字段显示为单选按钮,而不是默认复选框

将django表单中的布尔模型字段显示为单选按钮,而不是默认复选框,django,django-forms,validation,Django,Django Forms,Validation,我就是这样做的,在表单中将布尔模型字段显示为单选按钮Yes和No choices = ( (1,'Yes'), (0,'No'), ) class EmailEditForm(forms.ModelForm): #Display radio buttons instead of checkboxes to_send_form = forms.ChoiceField(choices=choices,widget=forms.Radio

我就是这样做的,在表单中将布尔模型字段显示为单选按钮Yes和No

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
正如您在上面的代码中所看到的,我需要一个干净的方法将输入字符串转换为整数,这可能是不必要的

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


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

使用
TypedChoiceField

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

如果需要水平渲染器,请使用此选项


如果您想处理布尔值而不是整数值,那么这就是解决方法

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

请注意,选项是成对的序列(请参阅)。不太清楚成对的是什么,tho。我在widgets.py中查看了,choices是一个形式的元组列表(choice_值,choice_标签)。我认为Daniel的解决方案更好。。。。我不认为这会强迫提交的值返回bool。这个答案没有说明它应该放在模型中还是表单中。我对django表单有些陌生,我想看看这是否可行,在哪里可行?@StevenRogers这是一个表单字段而不是模型字段;因此,它表示django表单中的一个字段,其中多个字段组成一个表单。另一方面,模型字段表示数据库表的列。
forms.TypedChoiceField(
    choices=((True, 'Yes'), (False, 'No')),
    widget=forms.RadioSelect,
    coerce=lambda x: x == 'True'
)