我有一个ManyToManyField
, 显示有复选框。share_data
当我的布尔字段等于 1时,应检查复选框。
这是代码:
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
输出:
[True, True, True]
(1L, u'my super brand', True)
(2L, u'new brand', True)
(3L, u'just my brand', True)
目前,只有第一个复选框被选中,即使所有都应该被选中,如输出中所示。怎么了?