Django - Show a BooleanField as part of a set as one group of radio buttons

I have the following models:

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) 

I use Phone in ModelForm as a set of forms. What I'm trying to do is show Phone.primary as a switch next to each instance of Phone . If I do basic as a RadioSelect widget:

 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', ) 

It will display two reports and they will be grouped together next to each instance. Instead, I'm looking for a way to show only one radio button next to each instance (which should set primary=True for this instance) and have the whole set of radio buttons grouped together so that only one of them can be selected.

I am also looking for a clean way to do this, I can do most of it manually - in my head - but I am wondering if there is a better way to do this, django style way.

Anyone got an idea?

+4
source share
1 answer

Well, you have two dilemmas. First, you need to group all the radio stations from different forms by providing them with the same HTML name attribute. I did this with an override of add_prefix .

Then you need to make sure that the "primary" field in your message data returns something meaningful from which you can determine which phone was selected (there should be only one "name" value in b / c POST data, you can select only one switch from the group). By assigning the correct prefix value (you need to do this under _init _ so that you can access the self instance), you can associate the "primary" value with the rest of its form data (via a special save method).

I tested the formset with the following and it spat out the correct html. So 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 
+3
source

Source: https://habr.com/ru/post/1402101/


All Articles