Django表单继承不起作用__init__

时间:2014-01-10 11:01:08

标签: python django django-forms

我有一个表单,我希望所有其他表单都可以继承,下面是我尝试的但是我收到一个错误,表明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',

        )

3 个答案:

答案 0 :(得分:2)

您的AbstractFormBase类不与继承树中的其他类合作。您的SchemeForm课程有一个特定的MRO,一个方法解析顺序。 super()调用只会按该顺序调用下一个 __init__方法,AbstractFormBase是下一个方法(后跟NgModelFormMixin和{{ 1}})。

您希望使用forms.ModelForm类中的__init__super()调用传递给MRO中的下一个班级:

AbstractFormBase

请注意,同样适用于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类具有Metafields属性(请参阅{ {3}}。)

答案 1 :(得分:1)

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)

答案 2 :(得分:1)

您的Base表单需要从forms.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')