newforms: apply_changes

9 views
Skip to first unread message

SmileyChris

unread,
Dec 28, 2006, 6:02:00 PM12/28/06
to Django developers
It seems like the newly added apply_changes method (to
form_for_instance) could be useful in other cases too if it was a bit
more "open-minded".

I don't see why apply_changes should bother about creating a field list
again when that has already been done in form_for_instance. Can't it
just use the fields in the Form?

How about if form_for_instance just set something like
`default_instance` for the form and apply_changes was made available to
all Forms. New method for BaseForm:

def apply_changes(self, instance=None, save=True):
if not instance:
instance = getattr(self, 'default_instance', None)
if not instance:
raise ValueError('An instance is required')
for field in self.fields.keys():
setattr(instance, f.attname, clean_data[f.name])
if save:
instance.save()
return instance

Adrian Holovaty

unread,
Dec 29, 2006, 12:57:46 AM12/29/06
to django-d...@googlegroups.com
On 12/28/06, SmileyChris <smile...@gmail.com> wrote:
> How about if form_for_instance just set something like
> `default_instance` for the form and apply_changes was made available to
> all Forms. New method for BaseForm:
>
> def apply_changes(self, instance=None, save=True):
> if not instance:
> instance = getattr(self, 'default_instance', None)
> if not instance:
> raise ValueError('An instance is required')
> for field in self.fields.keys():
> setattr(instance, f.attname, clean_data[f.name])
> if save:
> instance.save()
> return instance

This wouldn't work, because self.fields is a dictionary of newforms
Field objects, *not* database Field objects. The "f.attname" wouldn't
be available.

Adrian

--
Adrian Holovaty
holovaty.com | djangoproject.com

SmileyChris

unread,
Dec 29, 2006, 2:45:54 PM12/29/06
to Django developers
On Dec 29, 6:57 pm, "Adrian Holovaty" <holov...@gmail.com> wrote:
> This wouldn't work, because self.fields is a dictionary of newforms
> Field objects, *not* database Field objects. The "f.attname" wouldn't
> be available.

It was just concept code to see if there was any merit in the idea. If
you think there is a benefit still then I can write up a proper patch.

It still would work - you could get the _meta from the model of the
passed instance and compare f.name to find the matching database field.

SmileyChris

unread,
Jan 4, 2007, 8:48:08 PM1/4/07
to Django developers
Patch created: http://code.djangoproject.com/ticket/3232

On Dec 30 2006, 8:45 am, "SmileyChris" <smileych...@gmail.com> wrote:
> On Dec 29, 6:57 pm, "Adrian Holovaty" <holov...@gmail.com> wrote:
>
> > This wouldn't work, because self.fields is a dictionary of newforms
> > Field objects, *not* database Field objects. The "f.attname" wouldn't

> > be available.It was just concept code to see if there was any merit in the idea. If

Reply all
Reply to author
Forward
0 new messages