Login

shortcut for saving newforms to model

Author:
james_027
Posted:
September 7, 2007
Language:
Python
Version:
.96
Score:
5 (after 7 ratings)

I come up with this short cut of saving data from newforms to a model, for newforms that contains attributes from several models or some attributes that doesn't found in a model attributes

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. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 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()

#

Please login first before commenting.