[Answered ]-Get queryset for ModelMultipleChoiceField field based on ModelChoiceField

2👍

The error you’re seeing is most probably because the Form does not receive a ‘tours’ argument (it will receive a dictionary named data instead, containing the fields’ data in an unvalidated form) and thus the qs variable will be None.

You should probably do something like this:

class MyForm(forms.Form):
    tag = forms.ModelChoiceField(queryset=Tag.objects.all())
    tours = forms.ModelMultipleChoiceField(queryset=Tour.objects.none())

    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)

        if kwargs['data']:
            tag_id = kwargs['data'].get('tag', None)
            if tag_id:
                self.fields['tours'].queryset = Tour.objects.filter(tag_id=tag_id)

Note that we bypass django’s form mechanics a bit here and need to parse the tag_id ourselves. It’s not a big deal, though.

From a UX vantage point, this is a rather hard problem to get right without the use of ajax. So I wouldn’t completely dismiss your solution either.

👤Nuschk

Leave a comment