- 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
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
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.
#
that only works if all the attributes of the form is found in the model also.
#
Thansk a thousands. Lovely.
#
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.
#
Please login first before commenting.