Try:
self.fields['fieldname'].initial="value"
self
is keyword. you are missing that
Вопрос
My code is below. I am actually redefining my vehicle_make
just to change its initial value in the inherited class (UpdateForm). I am looking for a DRY approach. I tried field['fieldname'].initial="value", but that gives 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
Решение
Try:
self.fields['fieldname'].initial="value"
self
is keyword. you are missing that
Другие советы
Why don't you simply use the get_initial
method?