以django形式显示布尔模型字段作为单选按钮,而不是默认的复选框 [英] Display a boolean model field in a django form as a radio button rather than the default Checkbox

查看:378
本文介绍了以django形式显示布尔模型字段作为单选按钮,而不是默认的复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我怎么做的,以单选按钮Yes和No显示一个布尔模型字段。

This is how I went about, to display a Boolean model field in the form as Radio buttons Yes and 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

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

As you can see in the code above, I need a clean method that converts input string to an integer, which may be unnecessary.

做一个更好和/或djangoic的方法。如果是这样,那么如何?

Is there a better and/or djangoic way to do this. If so, how?

而不,使用 BooleanField 似乎引起更多的问题。对我来说似乎很明显但不是。为什么是这样的。

And no, using BooleanField seems to cause a lot more problems. Using that seemed obvious to me; but it isn't. Why is it so.

推荐答案

使用 TypedChoiceField

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

这篇关于以django形式显示布尔模型字段作为单选按钮,而不是默认的复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆