2006-11-25 14:33:59 +08:00
|
|
|
"""
|
2006-12-15 13:46:11 +08:00
|
|
|
Helper functions for creating Form classes from Django models
|
|
|
|
and database field objects.
|
2006-11-25 14:33:59 +08:00
|
|
|
"""
|
|
|
|
|
2006-12-15 13:46:11 +08:00
|
|
|
from forms import BaseForm, DeclarativeFieldsMetaclass, SortedDictFromList
|
|
|
|
|
2006-11-25 14:33:59 +08:00
|
|
|
__all__ = ('form_for_model', 'form_for_fields')
|
|
|
|
|
2006-12-16 06:33:24 +08:00
|
|
|
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
|
|
|
|
|
2006-12-17 13:12:53 +08:00
|
|
|
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.
|
|
|
|
"""
|
2006-12-15 13:46:11 +08:00
|
|
|
opts = model._meta
|
2006-12-16 05:22:13 +08:00
|
|
|
field_list = []
|
|
|
|
for f in opts.fields + opts.many_to_many:
|
|
|
|
formfield = f.formfield()
|
|
|
|
if formfield:
|
|
|
|
field_list.append((f.name, formfield))
|
|
|
|
fields = SortedDictFromList(field_list)
|
2006-12-17 13:12:53 +08:00
|
|
|
form = form or BaseForm
|
|
|
|
return type(opts.object_name + 'Form', (form,), {'fields': fields, '_model': model, 'create': create})
|
2006-11-25 14:33:59 +08:00
|
|
|
|
|
|
|
def form_for_fields(field_list):
|
2006-12-15 13:46:11 +08:00
|
|
|
"Returns a Form class for the given list of Django database field instances."
|
|
|
|
fields = SortedDictFromList([(f.name, f.formfield()) for f in field_list])
|
|
|
|
return type('FormForFields', (BaseForm,), {'fields': fields})
|