shortcut for saving newforms to model

1
2
3
4
def form_to_model_save(model, form):
    for key in form.cleaned_data:
        setattr(model, key, form.cleaned_data[key])
    model.save()

More like this

  1. Change model field attribute in a DRY way by jedie 2 years, 6 months ago
  2. Property Attributes in Memcache by ori 2 years, 5 months ago
  3. Newforms customs validators by baptiste 7 years, 1 month ago
  4. change a widget attribute in ModelForm without define the field by jedie 5 years, 8 months ago
  5. Type less with newforms admin by ncw 5 years, 8 months ago

Comments

scadink (on September 7, 2007):

Couldn't this be accomplished by doing:

Model(**form.cleaned_data)

Doesn't the double star make it like passing in kwargs. Anyway, that might be an even better shortcut if it works.

#

james_027 (on September 9, 2007):

that only works if all the attributes of the form is found in the model also.

#

lukas (on March 4, 2008):

Thansk a thousands. Lovely.

#

lukas (on March 9, 2008):

This doesn't work if you pass it a new (empty) instance and try to add data to a many_to_many relation (as the instance doesn't have a PK yet). We work around it with excepting a ValueError, save the instance without the m2m-relation, add it aftwarwards and save again. Not the most beautiful, but works for us.

def form_to_model_save(modelObject, form):
    """
    Updates a Django ORM Object modelObject with values from the form
    """

    # If we want to save many_to_many-relations on newly created
    # objects, we first have to save it w/o the relation so that it has
    # a primary key. Only then we can add the m2m-relation

    postponed = {}
    for key in form.cleaned_data:
        try:
            setattr(modelObject, key, form.cleaned_data[key])
        except ValueError, e:
            postponed[key] = form.cleaned_data[key]
    modelObject.save()

    for key in postponed:
        setattr(modelObject, key, postponed[key])
    modelObject.save()

#

(Forgotten your password?)