[英]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
是下一个(紧随其后的是NgModelFormMixin
和forms.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
类具有fields
或exclude
属性(请参阅选择要使用的字段 。)
将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.