[Fixed]-Django: Check multiple choices with not fixed choices

1👍

Give the form an __init__ method that gets a CarBrand as a parameter, then set the queryset to choose from based on that:

class CarForm(forms.Form):
    def __init__(self, car_brand, *args, **kwargs):
        self.fields['cars'] = forms.ModelMultipleChoiceField(
            queryset=CarModel.objects.filter(brand=car_brand),
            widget=forms.CheckboxSelectMultiple)
        super(CarForm, self).__init__(*args, **kwargs)

Now in your view get the relevant CarBrand instance for the page first, the create the form with CarForm(car_brand, request.POST) etc.

Leave a comment