From f96e933534501fd98f84cc53bcac62beaa72dbf2 Mon Sep 17 00:00:00 2001 From: Russell Keith-Magee Date: Sun, 5 Aug 2007 07:39:36 +0000 Subject: Fixed #4001 -- Added dynamic save_m2m method() to forms created with form_for_model and form_for_instance on save(commit=False). git-svn-id: http://code.djangoproject.com/svn/django/trunk@5804 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- django/newforms/models.py | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) (limited to 'django') diff --git a/django/newforms/models.py b/django/newforms/models.py index 56a08bc58e..7a86e30b1d 100644 --- a/django/newforms/models.py +++ b/django/newforms/models.py @@ -35,17 +35,23 @@ def save_instance(form, instance, fields=None, fail_message='saved', commit=True if fields and f.name not in fields: continue setattr(instance, f.name, cleaned_data[f.name]) - if commit: - instance.save() + # Wrap up the saving of m2m data as a function + def save_m2m(): + opts = instance.__class__._meta + cleaned_data = form.cleaned_data for f in opts.many_to_many: if fields and f.name not in fields: continue if f.name in cleaned_data: setattr(instance, f.attname, cleaned_data[f.name]) - # GOTCHA: If many-to-many data is given and commit=False, the many-to-many - # data will be lost. This happens because a many-to-many options cannot be - # set on an object until after it's saved. Maybe we should raise an - # exception in that case. + if commit: + # If we are committing, save the instance and the m2m data immediately + instance.save() + save_m2m() + else: + # We're not committing. Add a method to the form to allow deferred + # saving of m2m data + form.save_m2m = save_m2m return instance def make_model_save(model, fields, fail_message): -- cgit v1.3