Django ModelForm fails validation with no errors
If u still want to validate the object that was in the database, you can serialize it first and then create the Form with it.
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 is probably not the best way to do it but the only one that I have found to get a bound form from a model. I need it because I want to validate the current data in the database. I create a question since I don't think this is the best way of doing it:
Transform an unbound form to a bound one?
Note that your link doesn't call f.is_valid()
, it just saves directly. This is potentially a bit misleading.
The point is that instantiating a form with just an instance
parameter but no data
does not bind it to data, and the form is therefore not valid. You will see that f.is_bound
is False.
Behind the scenes, instance
is really just the same as passing initial
data, which as the docs note is only used to display the data initially and is not used for saving. You would probably benefit from reading the notes on bound and unbound forms.