mirror of
https://github.com/django/django.git
synced 2025-10-31 09:41:08 +00:00
newforms: Implemented apply_changes() method for form_for_instance Forms
git-svn-id: http://code.djangoproject.com/svn/django/trunk@4253 bcc190cf-cafb-0310-a4f2-bffc1f526a37
This commit is contained in:
@@ -20,6 +20,22 @@ def create(self, save=True):
|
||||
obj.save()
|
||||
return obj
|
||||
|
||||
def make_apply_changes(opts, instance):
|
||||
"Returns the apply_changes() method for a form_for_instance Form."
|
||||
from django.db import models
|
||||
def apply_changes(self, save=True):
|
||||
if self.errors:
|
||||
raise ValueError("The %s could not be changed because the data didn't validate." % opts.object_name)
|
||||
clean_data = self.clean_data
|
||||
for f in opts.fields + opts.many_to_many:
|
||||
if isinstance(f, models.AutoField):
|
||||
continue
|
||||
setattr(instance, f.attname, clean_data[f.name])
|
||||
if save:
|
||||
instance.save()
|
||||
return instance
|
||||
return apply_changes
|
||||
|
||||
def form_for_model(model, form=BaseForm):
|
||||
"""
|
||||
Returns a Form class for the given Django model class.
|
||||
@@ -45,12 +61,13 @@ def form_for_instance(instance, form=BaseForm):
|
||||
opts = model._meta
|
||||
field_list = []
|
||||
for f in opts.fields + opts.many_to_many:
|
||||
current_value = getattr(instance, f.attname)
|
||||
current_value = f.value_from_object(instance)
|
||||
formfield = f.formfield(initial=current_value)
|
||||
if formfield:
|
||||
field_list.append((f.name, formfield))
|
||||
fields = SortedDictFromList(field_list)
|
||||
return type(opts.object_name + 'InstanceForm', (form,), {'fields': fields, '_model': model})
|
||||
return type(opts.object_name + 'InstanceForm', (form,),
|
||||
{'fields': fields, '_model': model, 'apply_changes': make_apply_changes(opts, instance)})
|
||||
|
||||
def form_for_fields(field_list):
|
||||
"Returns a Form class for the given list of Django database field instances."
|
||||
|
||||
Reference in New Issue
Block a user