这就是我的方法,在表单中显示一个布尔模型字段作为单选按钮是和否.
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似乎会导致更多问题.使用它对我来说似乎很明显; 但事实并非如此.为什么会如此.