python - Django 将 kwargs 传递给继承的表单会导致错误(通用 UpdateView)

标签 python django forms generics

当我使用 django 通用 View - UpdateView 并尝试像这样更新表单 kwargs 时:

#views.py

from .forms import SomeInheritedForm
from .models import SomeModel

from django.views.generic import UpdateView

class SomeUpdateView(UpdateView):
    model = SomeModel
    form_class = SomeInheritedForm

    def get_form_kwargs(self, **kwargs):
        kwargs = super(SomeUpdateView, self).get_form_kwargs(**kwargs)
        kwargs['workspace'] = 'whatever'
        return kwargs

#forms.py

from .models import SomeModel

from django import forms

class ParentForm(forms.Form):
    def __init__(self, *args, **kwargs):
        self.workspace = kwargs.pop('workspace', None)
        super(ParentForm, self).__init__(*args, **kwargs)

class InheritedForm(forms.ModelForm, ParentForm):
    class Meta:
        model = SomeModel

这会给出这样的错误:

Django Version: 1.7.2
Exception Type: TypeError
Exception Value:    
__init__() got an unexpected keyword argument 'workspace'
Exception Location: /[ommited]/my_venv/local/lib/python2.7/site-packages/django/views/generic/edit.py in get_form, line 45
Python Executable:  /[ommited]/my_venv/bin/python
Python Version: 2.7.3

但是,如果我在 InheritedForm 中声明 __init__ ,它将正常工作。但是,如果有更多继承的形式,我就必须复制代码,这违反了 DRY 原则。

最佳答案

Python 总是尝试通过 MRO 查找方法,这基于父类声明的顺序。因此,在这种情况下,由于您将 ModelForm 放在类定义中的第一个位置,它会首先找到 __init__ ,因此会出现错误。

解决办法就是交换顺序:

class InheritedForm(ParentForm, forms.ModelForm):

虽然我确实想知道为什么你首先将 ParentForm 声明为从 forms.Form 继承 - 也可能让它从 ModelForm 继承,那么你不需要 InheritedForm 中的多重继承。

关于python - Django 将 kwargs 传递给继承的表单会导致错误(通用 UpdateView),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29301435/

相关文章:

python - 通过python脚本控制第三方应用程序时等待用户输入

python - 如何将 .tsv 转换为 .csv?

python - 如何将 mock_open 与 Python UnitTest 装饰器一起使用?

django - 如何使用 LaTeX 以编程方式生成 PDF?

javascript - 具有简单插值的django javascript翻译

javascript - 我的ajax表单没有提交

javascript - 表单的 Post 请求将空的 ImmutableMultiDict 返回到 Flask

python - Django SECRET_KEY 是针对每个实例还是针对每个应用?

django - 值对于类型字符变化来说太长(30)

javascript - Vue : Best approach to access possible existing nested properties in error object