1
0
mirror of https://github.com/django/django.git synced 2025-10-24 22:26:08 +00:00

newforms: The Form classes created by form_for_model() now have a create() method, which creates a model instance from the clean_data

git-svn-id: http://code.djangoproject.com/svn/django/trunk@4216 bcc190cf-cafb-0310-a4f2-bffc1f526a37
This commit is contained in:
Adrian Holovaty
2006-12-15 22:33:24 +00:00
parent a23e67bf4b
commit 4f5170bffe
2 changed files with 67 additions and 1 deletions

View File

@@ -7,6 +7,15 @@ from forms import BaseForm, DeclarativeFieldsMetaclass, SortedDictFromList
__all__ = ('form_for_model', 'form_for_fields')
def create(self, save=True):
"Creates and returns model instance according to self.clean_data."
if self.errors:
raise ValueError("The %s could not be created because the data didn't validate." % self._model._meta.object_name)
obj = self._model(**self.clean_data)
if save:
obj.save()
return obj
def form_for_model(model):
"Returns a Form class for the given Django model class."
opts = model._meta
@@ -16,7 +25,7 @@ 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_opts': opts})
return type(opts.object_name + 'Form', (BaseForm,), {'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."