gpt4 book ai didi

Django - 将表单集中的 BooleanField 显示为一组单选按钮

转载 作者:行者123 更新时间:2023-12-04 15:25:42 25 4
gpt4 key购买 nike

我有以下型号:

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)

我正在使用 Phone在 ModelForm 中作为表单集。我想要做的是显示 Phone.primary作为 Phone 的每个实例旁边的单选按钮.如果我将主要设置为 RadioSelect小部件:
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),并将所有单选按钮组合在一起,以便只能选择其中一个.

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

有人有想法吗?

最佳答案

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

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

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

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 显示为一组单选按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9759306/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com