问题
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:
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.
来源:https://stackoverflow.com/questions/41575870/django-check-multiple-choices-with-not-fixed-choices