I have a ManyToManyField
, displayed with checkboxes. Checkboxes should be checked when my boolean field share_data
is equal to one.
Here is the code:
class Participant(models.Model):
databases = models.ManyToManyField(Advertiser, null=True, blank=True, through='ShareDataToBrands')
@property
def share_to_brands_list(self):
brands=[]
for brand in ShareDataToBrands.objects.all():
brands.append((brand.advertiser.id, brand.advertiser.brand_name, brand.share_data))
return brands
class ShareDataToBrands(models.Model):
participant = models.ForeignKey(Participant, blank=False, null=False)
advertiser = models.ForeignKey(Advertiser, blank=False, null=False)
share_data= models.BooleanField(default=True)
def __str__(self):
return self.participant, self.advertiser, self.share_data
class ShareDataToBrandsForm(forms.ModelForm):
class Meta:
model = models.Participant
fields = ('databases', )
databases=forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple)
def __init__(self, *args, **kwargs):
super(ShareDataToBrandsForm, self).__init__(*args, **kwargs)
share_to_brands=self.instance.share_to_brands_list
self.fields['databases'].choices=self.fields['databases'].choices=[(brand[0], brand[1]) for brand in share_to_brands]
self.initial['databases']=[brand[2] for brand in share_to_brands]
print(self.initial['databases'])
for brand in self.instance.share_to_brands_list:
print brand
The output:
[True, True, True]
(1L, u'my super brand', True)
(2L, u'new brand', True)
(3L, u'just my brand', True)
Currently, only the first checkbox is checked, even though all should be checked as seen in the output. What's wrong?
I think when setting initial values for a CheckboxSelectMultiple
widget, you need to pass a list of values that should be checked, rather than a list of booleans for each option. So doing initial = [True,True,True]
doesn't get you the boxes checked. You want to do something more like initial = [1,2,3]
.
In your example, you might replace the relevant line with:
self.initial['databases']=[brand[0] for brand in share_to_brands if brand[2]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With