Azi*_*ari 6 django django-models django-forms django-widget
我有以下型号:
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)
Run Code Online (Sandbox Code Playgroud)
我Phone在ModelForm中用作formset.我要做的是Phone.primary在每个实例旁边显示一个单选按钮Phone.如果我将primary作为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', )
Run Code Online (Sandbox Code Playgroud)
它将显示两个单选按钮,它们将在每个实例旁边组合在一起.相反,我正在寻找一种方法,只显示每个实例旁边的一个单选按钮(应该primary=True为该实例设置),并将所有单选按钮组合在一起,以便只能选择其中一个.
我也在寻找一种干净的方法来做到这一点,我可以手动完成上述大部分操作 - 在我的脑海中 - 但我很想知道是否有更好的方法来实现它,这是一种django风格的方式.
有人有个主意吗?
好吧,你有两个困境。首先,您需要通过为不同表单集中的所有单选选择提供相同的 HTML 名称属性来对它们进行分组。我通过下面的add_prefix覆盖做到了这一点。
然后,您必须确保帖子数据中的“主要”字段返回一些有意义的内容,您可以从中确定选择了哪部手机(POST 数据中应该只有一个“名称”值,因为您只能选择一个)组内的单选按钮)。通过分配正确的前缀值(这需要在_ 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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1744 次 |
| 最近记录: |