shortcut for saving newforms to model

September 7, 2007
newforms model
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

def form_to_model_save(model, form):
    for key in form.cleaned_data:
        setattr(model, key, form.cleaned_data[key])

More like this

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


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.