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

后端 未结 1 638
梦毁少年i
梦毁少年i 2021-01-05 13:18

I have the following models:

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

    def primary_phone(self):
        return self         


        
相关标签:
1条回答
  • 2021-01-05 13:49

    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
    
    0 讨论(0)
提交回复
热议问题