Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在多对多关系上使用django MultipleChoiceField上的初始值_Python_Django - Fatal编程技术网

Python 在多对多关系上使用django MultipleChoiceField上的初始值

Python 在多对多关系上使用django MultipleChoiceField上的初始值,python,django,Python,Django,在我的模型中,我有: flowcell = models.ForeignKey("FlowCell", on_delete=models.PROTECT) lanes = models.ManyToManyField("main.FlowCellLane", related_name='demuxers', blank=True) 在我的表格中,我希望这些是可选择的,基于可用的流线。因此,我将flowcell弹出到一个变量,并使用它查看

在我的模型中,我有:

    flowcell = models.ForeignKey("FlowCell", on_delete=models.PROTECT)

    lanes = models.ManyToManyField("main.FlowCellLane", related_name='demuxers', blank=True)
在我的表格中,我希望这些是可选择的,基于可用的流线。因此,我将flowcell弹出到一个变量,并使用它查看有哪些“车道”:

class DemuxerForm(forms.ModelForm):
    class Meta:
        model = Demuxer
        exclude = ["owner", "pid", "flowcell"]

    lanes = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple)

    def __init__(self, *args, **kwargs):
        self.flowcell = kwargs.pop('flowcell')
        super().__init__(*args, **kwargs)
        self.fields['lanes'].choices = sorted([(lane.pk, str(lane.lane_number))
                                               for lane in self.flowcell.lanes.all()])
现在我想勾选所有可用的复选框。但我不知道我怎么能做到。在initial=可能的位置,“self”不可用。。。有什么想法吗?

我想出来了:

choices = self.flowcell.lanes.values_list("pk", lane_number").order_by("lane_number")
self.fields['lanes'].choices = choices
self.fields["lanes"].initial = [pk for pk, _ in choices]