Django: Check multiple choices with not fixed choices

笑着哭i 提交于 2019-12-25 07:35:39

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!