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
- Callable short_description (or other Meaningful Method Attributes) by eternicode 1 year, 12 months ago
- Dynamic Models Revisited by Ben 5 years, 7 months ago
- change a widget attribute in ModelForm without define the field by jedie 4 years, 10 months ago
- RelatedMixin for Details and Updates with Related Object Lists by christhekeele 1 year ago
- Decouple 'help_text' attribute from field definition by kmike 2 years, 8 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.
#