以django形式过滤多对多字段的选择

filter choices for many to many field in form django

我希望“picking_person”只能从组的“成员”中选择。我尝试了一些 init 和过滤器,但找不到解决方案。配置文件模型不与组模型连接。组模型有两个连接到配置文件的属性:

class Group(models.Model):
 members = models.ManyToManyField(
        Profile, blank=True, default=Profile, related_name="members"
    )
 picking_person = models.ManyToManyField(
        Profile, blank=True, default=Profile, related_name="picking_person"
    )

forms.py:

class ChoosePersonPickingForm(ModelForm):
    class Meta:
        model = Group
        fields = ['picking_person']

views.py:

def choose_person_to_pick_players(request, pk):
    group = Group.objects.get(id=pk)
    form = ChoosePersonPickingForm(instance=group)
    group_members = group.members.all()
    if request.method == "POST":
        form = ChoosePersonPickingForm(request.POST, instance=group)
        form.save()
        return redirect('group', group.id)
    context = {'form': form}
    return render(request, "choose-picking-person.html", context)

你能帮我找到解决办法吗?

顺便说一句 - 您确定要 Picking Person 是 ManyToMany,一组中是否有多个人?

无论如何 - 由于每个表单的可选人员列表可能不同,您希望在表单中使用 init 函数来生成选项,因为它在表单实例化时被调用。您可以使用您已经传入的实例来帮助处理查询集。显然这仅适用于现有组。

class ChoosePersonPickingForm(ModelForm):

    picking_person_choices= None
    picking_person = forms.ModelMultipleChoiceField(label='Pick Person', queryset=picking_person_choices, required=True)  
    #could be a ModelChoiceField if picking_person not actually ManyToMany

    class Meta:
        model = Group
        fields = ['picking_person']

    def __init__(self, *args, **kwargs):
        super(ChoosePersonPickingForm, self).__init__(*args, **kwargs)
        self.picking_people_choices= Profile.objects.filter(members = self.instance)
        self.fields['picking_person'].queryset = self.picking_people_choices