django CheckboxSelectMultiple:我的复选框未被选中

时间:2015-11-08 18:59:33

标签: django checkbox multiplechoicefield

我有一个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)

目前,只检查第一个复选框,即使应在输出中看到所有复选框。怎么了?

1 个答案:

答案 0 :(得分:6)

我认为在设置CheckboxSelectMultiple小部件的初始值时,您需要传递应该检查的列表,而不是每个选项的布尔值列表。所以做initial = [True,True,True]不会让你检查框。你想做更像initial = [1,2,3]的事情。

在您的示例中,您可以将相关行替换为:

self.initial['databases']=[brand[0] for brand in share_to_brands if brand[2]]