I want to have a bound form from an object to use the is_valid method. The reason is because I have some old data that I want the users to correct according to the new validation rules. Then, I want to reuse the code of the clean methods in my form.
I ended up serializing my response:
from django.utils import simplejson
from django.core.serializers import serialize
(...)
fields_dict = simplejson.loads(serialize('json', [obj]))[0]['fields']
form = forms.MyForm(fields_dict)
if form.is_valid
This works but it doesn’t seem very Djangish. Also, it seems as a common problem so I was looking for a better way of doing this.
According to the documentation, translating data from an unbound form to a bound form is not meant to happen:
https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#the-save-method
However, that would be the easiest solution for me.
There is Django’s
django.forms.models.model_to_dictfunction that will convert your existing model instance into a dictionary of data suitable for binding to aModelForm.This would probably be more efficient, and definitely more “Djangish”, than serialising and unserialising the object.
And if you also create the form with the
instancekeyword, it will know to update the existing record when saved.So: