在Django中以DRY方式在继承类中设置字段属性

时间:2014-04-21 20:06:22

标签: django-forms django-class-based-views django-models

我的代码如下。我实际上是重新定义我的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

2 个答案:

答案 0 :(得分:0)

为什么不简单地使用get_initial方法?

答案 1 :(得分:0)

尝试:

self.fields['fieldname'].initial="value"

self是关键字。你错过了