Django窗体继承不起作用__

2024-09-30 01:21:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个表单,我希望所有其他表单都继承它,下面是我尝试过的,但是我得到了一个错误,它表明init不是从AbstractFormBase类运行的。SchemeForm“应该”在运行自己的参数之前继承所有__init__参数。在

错误:

'SchemeForm' object has no attribute 'fields'

代码已更新

^{pr2}$

Tags: no代码表单fields参数objectinit错误
3条回答

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

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

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

^{pr2}$

您的AbstractFormBase类与继承树中的其他类不合作。您的SchemeForm类有一个特定的MRO,一个方法解析顺序。super()调用将只按该顺序调用next__init__方法,AbstractFormBase是下一个方法(后跟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

基本窗体需要继承自窗体.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')

相关问题 更多 >

    热门问题