Django - 将表单集中的 BooleanField 显示为一组单选按钮 [英] Django - Show BooleanField in a formset as one group of radio buttons

查看:22
本文介绍了Django - 将表单集中的 BooleanField 显示为一组单选按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下型号:

class Profile(models.Model):
    verified = models.BooleanField(default=False)

    def primary_phone(self):
        return self.phone_set.get(primary=True)

class Phone(models.Model):
    profile = models.ForeignKey(Profile)
    type = models.CharField(choices=PHONE_TYPES, max_length=16)
    number = models.CharField(max_length=32)
    primary = models.BooleanField(default=False)

    def save(self, force_insert=False, force_update=False, using=None):
        if self.primary:
            # clear the primary attribute of other phones of the related profile
            self.profile.phone_set.update(primary=False)
        self.save(force_insert, force_update, using)

我在 ModelForm 中使用 Phone 作为表单集.我想要做的是将 Phone.primary 显示为每个 Phone 实例旁边的单选按钮.如果我将主要设置为 RadioSelect 小部件:

I'm using Phone in a ModelForm as a formset. What I'm trying to do is to show Phone.primary as a radio button beside each instance of Phone. If I make primary as a RadioSelect widget:

class PhoneForm(ModelForm):
    primary = forms.BooleanField(widget=forms.RadioSelect( choices=((0, 'False'), (1, 'True')) ))

    class Meta:
        from accounts.models import Phone
        model = Phone
        fields = ('primary', 'type', 'number', )

它将显示两个单选按钮,它们将分组在每个实例旁边.相反,我正在寻找一种方法,在每个实例旁边仅显示一个单选按钮(应该为该实例设置 primary=True),并将所有单选按钮组合在一起,以便只能选择其中之一.

It will show two radio buttons, and they will be grouped together next to each instance. Instead, I'm looking for a way to show only one radio button next to each instance (which should set primary=True for that instance), and have all the set of radio buttons grouped together so that only one of them can be chosen.

我也在寻找一种干净的方法来做到这一点,我可以手动完成上述大部分工作 - 在我的脑海中 - 但我很想看看是否有更好的方法来做到这一点,django 风格方式.

I'm also looking for a clean way of doing this, I can do most of the above manually - in my head - but I'm interested to see if there is a better way to do it, a django-style way.

有人有想法吗?

推荐答案

好的,这里有两个难题.首先,您需要通过为它们提供相同的 HTML 名称属性来对来自不同表单集中的所有单选选项进行分组.我使用下面的 add_prefix 覆盖做到了这一点.

Ok you've got two dilemma's here. First is you need to group all radio selects from different formsets by giving them the same HTML name attribute. I did that with the add_prefix override below.

然后你必须确保你的帖子数据中的主要"字段返回一些有意义的东西,你可以从中确定选择了哪个电话(在 POST 数据 b/c 中应该只有一个名称"值,你可以仅从一组中选择一个单选按钮).通过分配适当的前缀值(这需要在 _init_ 下完成,以便您可以访问 self 实例),您将能够关联主要"value 与其表单数据的其余部分(通过自定义保存方法).

Then you have to make sure that the 'primary' field in your post data returns something meaningful, from which you can determine which phone was selected (there should only be one 'name' value in POST data b/c you can only select one radio button from within a group). By assigning the proper prefix value (this needs to be done under _init_ so you can access the self instance), you'll be able to associate the 'primary' value with the rest of its form data (through a custom save method).

我用以下内容测试了一个表单集,它吐出正确的 html.所以试试这个:

I tested a formset with the following and it spat out the right html. So give this a try:

class PhoneForm(ModelForm):
    def __init__ (self, *args, **kwargs)
        super(PerstransForm, self).__init__(*args, **kwargs)
        self.fields['primary'] = forms.BooleanField( widget = forms.RadioSelect(choices=((self.prefix, 'This is my Primary Phone'),))

    #enter your fields except primary as you had before.
    def add_prefix(self, field):
        if field == 'primary': return field
        else: return self.prefix and ('%s-%s' % (self.prefix, field)) or field

这篇关于Django - 将表单集中的 BooleanField 显示为一组单选按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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