diff --git a/django/newforms/models.py b/django/newforms/models.py index c8947b78b2..6b111d7ee1 100644 --- a/django/newforms/models.py +++ b/django/newforms/models.py @@ -16,8 +16,12 @@ def create(self, save=True): obj.save() return obj -def form_for_model(model): - "Returns a Form class for the given Django model class." +def form_for_model(model, form=None): + """ + Returns a Form class for the given Django model class. + + Provide 'form' if you want to use a custom BaseForm subclass. + """ opts = model._meta field_list = [] for f in opts.fields + opts.many_to_many: @@ -25,7 +29,8 @@ def form_for_model(model): if formfield: field_list.append((f.name, formfield)) fields = SortedDictFromList(field_list) - return type(opts.object_name + 'Form', (BaseForm,), {'fields': fields, '_model': model, 'create': create}) + form = form or BaseForm + return type(opts.object_name + 'Form', (form,), {'fields': fields, '_model': model, 'create': create}) def form_for_fields(field_list): "Returns a Form class for the given list of Django database field instances." diff --git a/tests/modeltests/model_forms/models.py b/tests/modeltests/model_forms/models.py index f86382abc4..5ffd6aac9f 100644 --- a/tests/modeltests/model_forms/models.py +++ b/tests/modeltests/model_forms/models.py @@ -29,7 +29,7 @@ class Article(models.Model): return self.headline __test__ = {'API_TESTS': """ ->>> from django.newforms import form_for_model +>>> from django.newforms import form_for_model, BaseForm >>> Category.objects.all() [] @@ -101,4 +101,13 @@ Traceback (most recent call last): ... ValueError: The Category could not be created because the data didn't validate. +You can pass a custom Form class to form_for_model. Make sure it's a +subclass of BaseForm, not Form. +>>> class CustomForm(BaseForm): +... def say_hello(self): +... print 'hello' +>>> CategoryForm = form_for_model(Category, form=CustomForm) +>>> f = CategoryForm() +>>> f.say_hello() +hello """}