Home > OS >  filter choices for many to many field in form django
filter choices for many to many field in form django

Time:05-27

I want "picking_person" to be selectable only from "members" of a Group. I ill trying some init and filters, but i cannot find solution. Profile model does not connected with Group model. Group model have two attributes which are connected to Profile:

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)

Can you help me to find solution?

CodePudding user response:

Just as an aside - are you sure you want Picking Person to be ManyToMany, is there more than one in a group?

Anyhow - as the list of pickable persons may be different for each form, you want to use the init function in your form to generate the options as it is called when the form instantiates. You can use the instance you are already passing in to help with the queryset. Obviously this will only work for an existing group.

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


        
  • Related