2024-09-30 01:21:10 发布
网友
我有一个表单,我希望所有其他表单都继承它,下面是我尝试过的,但是我得到了一个错误,它表明init不是从AbstractFormBase类运行的。SchemeForm“应该”在运行自己的参数之前继承所有__init__参数。在
AbstractFormBase
__init__
错误:
'SchemeForm' object has no attribute 'fields'
代码已更新:
将forms.ModelForm放在基类列表的第一位:
forms.ModelForm
class SchemeForm(forms.ModelForm, AbstractFormBase, NgModelFormMixin):
并添加object作为AbstractFormBase基类,并在init中添加super调用:
object
super
您的AbstractFormBase类与继承树中的其他类不合作。您的SchemeForm类有一个特定的MRO,一个方法解析顺序。super()调用将只按该顺序调用next__init__方法,AbstractFormBase是下一个方法(后跟NgModelFormMixin和{})。在
SchemeForm
super()
NgModelFormMixin
您希望通过使用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或{}属性(请参见selecting the fields to use)
form.ModelForm
Meta
fields
基本窗体需要继承自窗体.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')
将
forms.ModelForm
放在基类列表的第一位:并添加
^{pr2}$object
作为AbstractFormBase
基类,并在init中添加super
调用:您的})。在
AbstractFormBase
类与继承树中的其他类不合作。您的SchemeForm
类有一个特定的MRO,一个方法解析顺序。super()
调用将只按该顺序调用next__init__
方法,AbstractFormBase
是下一个方法(后跟NgModelFormMixin
和{您希望通过使用
AbstractFormBase
类中的super()
将__init__
调用传递给MRO中的下一个类:注意,这同样适用于}属性(请参见selecting the fields to use)
NgModelFormMixin
,并且form.ModelForm
要求Meta
类具有fields
或{基本窗体需要继承自窗体.ModelForm在
见http://chriskief.com/2013/06/30/django-form-inheritance/
相关问题 更多 >
编程相关推荐