编程语言
首页 > 编程语言> > python-Django ModelForm继承和元继承

python-Django ModelForm继承和元继承

作者:互联网

我有这个ModelForm:

class Event(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(Event, self).__init__(*args, **kwargs)
        ##Here make some changes such as:
        self.helper = FormHelper()
        self.helper.form_method = 'POST'
        ##Many settings here which **i don't want to rewrite in 10 child classes**

    class Meta:
        model = Event
        exclude = something...
        widgets = some settings here also.

而这个子ModelForm:

class UpgradedEvent(Event):

    def __init__(self, *args, **kwargs):
        super(UpgradedEvent,self).__init__(*args,**kwargs)

    class Meta(Event.Meta):
        model = UpgradedEvent

UpgradedEvent是事件模型的子级,但具有一些额外的字段.
如何将所有设置从事件表单继承到UpgradedEvent FORM中?

运行上面的代码时,它将呈现“事件”表单.有没有办法只继承__init__内部的设置?

EDIT

查看答案,它很好用,但请记住:
您需要在子类中创建另一个FormHelper实例,否则它将无法正常工作.因此,子类应类似于:

class UpgradedEvent(Event):

    def __init__(self, *args, **kwargs):
        super(UpgradedEvent,self).__init__(*args,**kwargs)
        self.helper = FormHelper()

    class Meta(Event.Meta):
        model = UpgradedEvent

解决方法:

创建FormWithSettings,它将保留表单类的通用设置并继承它

class FormWithSettings(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(FormWithSettings, self).__init__(*args, **kwargs)
        ##Here make some changes such as:
        self.helper = FormHelper()
        self.helper.form_method = 'POST'
        ##Many settings here which **i don't want to rewrite in 10 child classes**

    class Meta:
        exclude = something...
        widgets = some settings here also.

class EventForm(FormWithSettings):

    def __init__(self, *args, **kwargs):
        super(EventForm, self).__init__(*args,**kwargs)

    class Meta(FormWithSettings.Meta):
        model = Event

class UpgradedEventForm(FormWithSettings):

    def __init__(self, *args, **kwargs):
        super(UpgradedEventForm, self).__init__(*args,**kwargs)

    class Meta(FormWithSettings.Meta):
        model = UpgradedEvent

标签:inheritance,django-forms,python,django
来源: https://codeday.me/bug/20191025/1926435.html