From 684b0396cfff1c4343a83bd600db69af9188986d Mon Sep 17 00:00:00 2001 From: Carl Meyer Date: Tue, 7 Jun 2011 16:15:54 +0000 Subject: [PATCH] Fixed #14082 -- Use metaclass of provided ModelForm subclass in modelform_factory. Thanks jspiros and Stephen Burrows for the patch. git-svn-id: http://code.djangoproject.com/svn/django/trunk@16334 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- django/forms/models.py | 7 ++++++- .../model_forms_regress/tests.py | 18 +++++++++++++++++- 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/django/forms/models.py b/django/forms/models.py index ecfdc92182..b34f4d03e8 100644 --- a/django/forms/models.py +++ b/django/forms/models.py @@ -396,7 +396,12 @@ def modelform_factory(model, form=ModelForm, fields=None, exclude=None, 'formfield_callback': formfield_callback } - return ModelFormMetaclass(class_name, (form,), form_class_attrs) + form_metaclass = ModelFormMetaclass + + if issubclass(form, BaseModelForm) and hasattr(form, '__metaclass__'): + form_metaclass = form.__metaclass__ + + return form_metaclass(class_name, (form,), form_class_attrs) # ModelFormSets ############################################################## diff --git a/tests/regressiontests/model_forms_regress/tests.py b/tests/regressiontests/model_forms_regress/tests.py index f53600195b..9817858afc 100644 --- a/tests/regressiontests/model_forms_regress/tests.py +++ b/tests/regressiontests/model_forms_regress/tests.py @@ -4,7 +4,7 @@ from django import forms from django.core.exceptions import FieldError, ValidationError from django.core.files.uploadedfile import SimpleUploadedFile from django.forms.models import (modelform_factory, ModelChoiceField, - fields_for_model, construct_instance) + fields_for_model, construct_instance, ModelFormMetaclass) from django.utils import unittest from django.test import TestCase @@ -460,3 +460,19 @@ class EmptyFieldsTestCase(TestCase): self.assertTrue(form.is_valid()) instance = construct_instance(form, Person(), fields=()) self.assertEqual(instance.name, '') + + +class CustomMetaclass(ModelFormMetaclass): + def __new__(cls, name, bases, attrs): + new = super(CustomMetaclass, cls).__new__(cls, name, bases, attrs) + new.base_fields = {} + return new + +class CustomMetaclassForm(forms.ModelForm): + __metaclass__ = CustomMetaclass + + +class CustomMetaclassTestCase(TestCase): + def test_modelform_factory_metaclass(self): + new_cls = modelform_factory(Person, form=CustomMetaclassForm) + self.assertEqual(new_cls.base_fields, {})