4

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

目前,只有第一个复选框被选中,即使所有都应该被选中,如输出中所示。怎么了?

4

1 回答 1

9

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

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

self.initial['databases']=[brand[0] for brand in share_to_brands if brand[2]]
于 2015-11-11T15:20:44.470 回答