我的代码如下。我实际上是重新定义我的vehicle_make
只是为了改变继承类(UpdateForm)中的初始值。我正在寻找一种干燥的方法。我尝试了字段[' fieldname'] .initial =" value",但这给了keyerror。
class BaseInputForm(forms.ModelForm):
class Meta:
model = Vehicle
exclude = ('vehicle_make','vehicle_model')
def __init__(self, *args, **kwargs):
super(SearchInputForm, self).__init__(*args, **kwargs)
self.fields['vehicle_make']=forms.ChoiceField(
initial="NA",
label="Car make",
choices=MAKES,
widget=forms.Select(attrs={'id':'makes'})
)
class CreateForm(BaseInputForm):
pass
class UpdateForm(BaseInputForm):
def __init__(self, *args, **kwargs):
super(SearchUpdateForm, self).__init__(*args, **kwargs)
self.vehicle_make=self.instance.vehicle_make
self.fields['vehicle_make'] = forms.ChoiceField(
initial=self.vehicle_make,
label="Car make",
choices=MAKES,
widget=forms.Select(attrs={'id':'makes'})
)
#self.fields['vehicle_make'].initial=self.instance.vehicle_model
答案 0 :(得分:0)
为什么不简单地使用get_initial
方法?
答案 1 :(得分:0)
尝试:
self.fields['fieldname'].initial="value"
self
是关键字。你错过了