繁体   English   中英

Django表单继承不起作用__init__

[英]Django form inheritance not working __init__

我有一个我希望所有其他表单都继承的表单,下面是我尝试过的表单,但是出现错误,表明该初始化未从AbstractFormBase类运行。 SchemeForm“应”在运行自己的参数之前继承所有__init__参数。

错误:

'SchemeForm' object has no attribute 'fields'

代码已更新

class AbstractFormBase(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        self.helper = FormHelper()
        self.helper.form_class = 'form-horizontal'
        self.helper.label_class = 'col-lg-3'
        self.helper.field_class = 'col-lg-8'

class SchemeForm(AbstractFormBase, NgModelFormMixin,):
    def __init__(self, *args, **kwargs):
        super(SchemeForm, self).__init__(*args, **kwargs)
        self.helper.layout = Layout(
            'name',
            'domain',
            'slug',

        )

您的AbstractFormBase类与继承树中的其他类不配合。 您的SchemeForm类具有特定的MRO,即方法解析顺序。 super()调用只会按该顺序调用下一个 __init__方法,而AbstractFormBase是下一个(紧随其后的是NgModelFormMixinforms.ModelForm )。

您可能希望通过使用AbstractFormBase类中的super()__init__调用传递给MRO中的下一个类:

class AbstractFormBase(object):
    def __init__(self, *args, **kwargs):
        super(AbstractFormBase, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_class = 'form-horizontal'
        self.helper.label_class = 'col-lg-3'
        self.helper.field_class = 'col-lg-8'

请注意,这同样适用于NgModelFormMixin ,并且该form.ModelForm要求Meta类具有fieldsexclude属性(请参阅选择要使用的字段 。)

forms.ModelForm放在基类列表的第一位:

class SchemeForm(forms.ModelForm, AbstractFormBase, NgModelFormMixin):

并添加object作为AbstractFormBase基类,并在init中添加super调用:

class AbstractFormBase(object):
    def __init__(self, *args, **kwargs):
        super(AbstractFormBase, self).__init__(*args, **kwargs)

您的基本表单需要继承自form.ModelForm

参见http://chriskief.com/2013/06/30/django-form-inheritance/

class AbstractFormBase(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        self.helper = FormHelper()
        self.helper.form_class = 'form-horizontal'
        self.helper.label_class = 'col-lg-3'
        self.helper.field_class = 'col-lg-8's

    class Meta:
        model = MyModel
        fields = ('field1', 'field2')

class SchemeForm(AbstractFormBase, NgModelFormMixin,):
    def __init__(self, *args, **kwargs):
        super(AbstractFormBase, self).__init__(*args, **kwargs)
            self.helper.layout = Layout(
            'name',
            'domain',
            'slug',
        )

    class Meta(AbstractFormBase.Meta):
        model = MyModel   # Or some other model
        fields = ('field3', 'field4')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM