Django: Check multiple choices with not fixed choi

2019-09-14 23:20发布

I am new to Django, and I am trying to create a multiple selection with checkboxes. The problem is that all of the examples that I found have fixed choices that are specified in the form, and I don't need that.

More concretely, let this be a model for a simple car dealership app:

class CarBrand(models.Model):
    name = model.CharField()

class CarModel(models.Model):
    name = model.CharField()
    brand = model.ForeignKey(CarBrand)

My goal is when I enter the page for Audi, I get options A3, A4, A5, but when I enter the page for BMW, I get options M3, M4, M5. After clicking the submit it should send all the car models that were selected.

1条回答
乱世女痞
2楼-- · 2019-09-15 00:06

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.

查看更多
登录 后发表回答