【问题标题】:set field attributes in inherited classes in a DRY fashion in Django在 Django 中以 DRY 方式设置继承类中的字段属性
【发布时间】:2014-04-21 20:06:21
【问题描述】:

我的代码如下。我实际上正在重新定义我的vehicle_make,只是为了更改其在继承类(UpdateForm)中的初始值。我正在寻找一种 DRY 方法。我尝试了 field['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

【问题讨论】:

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


    【解决方案1】:

    试试:

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

    self 是关键字。你错过了

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2019-03-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多