Django - Show BooleanField in a formset as one group of radio buttons

白昼怎懂夜的黑 提交于 2019-11-30 20:48:08

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.

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).

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!