Django:检查多个选项,而不是固定的选择 [英] Django: Check multiple choices with not fixed choices
问题描述
我是Django的新手,我正尝试用复选框创建一个多重选择。问题是,我发现所有的例子都有固定的选择,在表单中指定,我不需要。
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)
我的目标是当我进入奥迪的页面时,我可以选择A3,A4,A5,但是当我进入宝马的页面时,我获取选项M3,M4,M5。点击提交后,应发送所有选择的车型。
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.
推荐答案
给表单一个 __init __
方法,获取CarBrand作为参数,然后根据以下条件设置查询器进行选择:
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)
在您的视图中,首先获取相关的CarBrand实例,创建具有 CarForm(car_brand ,request.POST)
等。
Now in your view get the relevant CarBrand instance for the page first, the create the form with CarForm(car_brand, request.POST)
etc.
这篇关于Django:检查多个选项,而不是固定的选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!