Patrick Altman 的解决方案仅适用于 常规 表单 - 如果您尝试使用 ModelForm 进行此操作,您将遇到元类冲突或缺少某些字段。
我发现的最简单和最短的解决方案是 Django 的附件ticket #7018 - 谢谢,bear330 :o)
你需要:
from django.forms.forms import get_declared_fields
. . .
class ParentsIncludedModelFormMetaclass(ModelFormMetaclass):
"""
Thanks to bear330 - taken from https://code.djangoproject.com/attachment/ticket/7018/metaforms.py
"""
def __new__(cls, name, bases, attrs):
# We store attrs as ModelFormMetaclass.__new__ clears all fields from it
attrs_copy = attrs.copy()
new_class = super(ParentsIncludedModelFormMetaclass, cls).__new__(cls, name, bases, attrs)
# All declared fields + model fields from parent classes
fields_without_current_model = get_declared_fields(bases, attrs_copy, True)
new_class.base_fields.update(fields_without_current_model)
return new_class
def get_next_in_mro(current_class, class_to_find):
"""
Small util - used to call get the next class in the MRO chain of the class
You'll need this in your Mixins if you want to override a standard ModelForm method
"""
mro = current_class.__mro__
try:
class_index = mro.index(class_to_find)
return mro[class_index+1]
except ValueError:
raise TypeError('Could not find class %s in MRO of class %s' % (class_to_find.__name__, current_class.__name__))
然后你将你的 mixin 定义为一个普通的 ModelForm,但是没有声明 Meta:
from django import forms
class ModelFormMixin(forms.ModelForm):
field_in_mixin = forms.CharField(required=True, max_length=100, label=u"Field in mixin")
. . .
# if you need special logic in your __init__ override as usual, but make sure to
# use get_next_in_mro() instead of super()
def __init__(self, *args, **kwargs):
#
result = get_next_in_mro(self.__class__, ModelFormMixin).__init__(self, *args, **kwargs)
# do your specific initializations - you have access to self.fields and all the usual stuff
print "ModelFormMixin.__init__"
return result
def clean(self):
result = get_next_in_mro(self.__class__, ModelFormMixin).clean(self)
# do your specific cleaning
print "ModelFormMixin.clean"
return result
最后 - 最终的 ModelForm,重用了 ModelFormMixin 的特性。
您应该定义 Meta 和所有常见的东西。在最终形式中,您可以调用 super(...)
当您覆盖方法时(见下文)。
注意:最终表单必须将 ParentsIncludedModelFormMetaclass 设置为元类
注意:类的顺序很重要 - 将 mixin 放在首位,然后是 ModelFrom。
class FinalModelForm(ModelFormMixin, forms.ModelForm):
"""
The concrete form.
"""
__metaclass__ = ParentsIncludedModelFormMetaclass
class Meta:
model = SomeModel
field_in_final_form = forms.CharField(required=True, max_length=100, label=u"Field in final form")
def clean(self):
result = super(FinalModelForm, self).clean()
# do your specific cleaning
print "FinalModelForm.clean"
return result
请记住,这仅在两个类都是 ModelForms 时才有效。如果您尝试使用这种技术混合和匹配 Form 和 ModelFrom,它根本不会漂亮:o)