我有一个页面,我在其中使用表单集显示不同的表单。
这些是我的模型:
class Phone(models.Model):
mac = models.CharField()
class PhoneLine(models.Model):
phone = models.ForeignKey(Phone)
voicemail = models.BooleanField("Voice Mail", default=False)
一部电话可以有多条线路(电话线),但只有一条电话线可以启用语音信箱。
默认情况下,当我使用 formset 显示电话线时,语音邮件字段显示为一个复选框,如下所示。(根据要求,我在 formset 中添加了前缀)
form1 of the formset
<input type="checkbox" name="phone_client_line_1-0-voicemail" id="id_phone_client_line_1-0-voicemail">
form2 of the formset
<input type="checkbox" name="phone_client_line_1-1-voicemail" id="id_phone_client_line_1-1-voicemail">
(复选框的选中和取消选中会更新后端)
基于这个线程,Django - Show BooleanField in a formset as a group of radio buttons,我修改了我的电话线表单的init和 add_prefix 方法,现在将语音邮件字段显示为单选按钮..
class PhoneLineForm(ModelForm):
def __init__ (self, *args, **kwargs):
super(PhoneLineForm, self).__init__(*args, **kwargs)
self.fields['voicemail'] = BooleanField( widget = RadioSelect(choices=((self.prefix+"-"+str("voicemail"), 'Voicemail LIne'),)))
def add_prefix(self, field):
if field == 'voicemail': return ('%s_%s') %(field, self.instance.phone.id)
else: return self.prefix and ('%s-%s' % (self.prefix, field)) or field
这会将 html 输出修改为以下内容:
form1 of the formset
<input type="radio" id="id_voicemail_1_0" value="phone_client_line_1-0-voicemail" name="voicemail_1">
form2 of the formset
<input type="radio" id="id_voicemail_1_0" value="phone_client_line_1-1-voicemail" name="voicemail_1">
如您所见,现在对于无线电字段 voicemail_1,我有所选电话线的值。如果我提交此表单,在我选择了 voicemail_1 收音机后,它不会更新数据库。
如何捕获提交时选择的电话线的值?如果我覆盖 phonelineform 的保存方法,它应该包含什么......?
对此的任何指示将不胜感激。谢谢!!