Login

shortcut for saving newforms to model

Author:
james_027
Posted:
September 7, 2007
Language:
Python
Version:
.96
Tags:
newforms model
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

Comments

scadink (on September 7, 2007):
<p>Couldn't this be accomplished by doing:</p> <p>Model(**form.cleaned_data)</p> <p>Doesn't the double star make it like passing in kwargs. Anyway, that might be an even better shortcut if it works.</p>

#

james_027 (on September 9, 2007):
<p>that only works if all the attributes of the form is found in the model also.</p>

#

lukas (on March 4, 2008):
<p>Thansk a thousands. Lovely.</p>

#

lukas (on March 9, 2008):
<p>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.</p> <pre>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() </pre>

#

Please login first before commenting.