我正在尝试将kwargs传递给我的forms.py文件,当表单加载时,我收到一条错误,说我的form_py文件中没有定义car_id。我知道这是因为下面的代码行,但我不知道如何解决它。
form = SelectCarModelForm()
forms.py
def __init__(self, *args, **kwargs):
self.car_id = kwargs.pop('car_id', None)
super(SelectCarModelForm, self).__init__(*args, **kwargs)
self.fields['car_model'] = forms.ModelChoiceField(
empty_label = "Select a Model",
queryset = CarModel.objects.filter(model=car_id),
widget = Select(attrs={'class': 'span12 small-margin-top small-margin-bottom'}),
required=True
)
视图
if request.method == "POST":
form = SelectCarModelForm(request.POST)
if form.is_valid():
model = form.cleaned_data['car_model']
# Go to the next form in the process.
return redirect('view_car')
# Initial form
else:
form = SelectCarModelForm()
return render(
request,
template_name = 'cars/forms/view_car_models.html',
dictionary = {
'form':form,
}
)
答案 0 :(得分:0)
你要么这样做:
# pass a `car_id` value when instantiating the form
form = SelectCarModelForm(car_id=<some_value>)
如果这不可行,也许这个:
def __init__(self, *args, **kwargs):
self.car_id = kwargs.pop('car_id', None)
super(SelectCarModelForm, self).__init__(*args, **kwargs)
if self.car_id is not None:
self.fields['car_model'] = forms.ModelChoiceField(
empty_label = "Select a Model",
queryset = CarModel.objects.filter(model=car_id),
widget = Select(attrs={'class': 'span12 small-margin-top small-margin-bottom'}),
required=True
)
else:
self.fields['car_model'] = forms.ModelChoiceField(
empty_label = "Select a Model",
queryset = CarModel.objects.filter(model=<SOME-OTHER-CRITERIA),
widget = Select(attrs={'class': 'span12 small-margin-top small-margin-bottom'}),
required=True
)