Reputation: 3338
I thought it would be easier to start using models form instead of regular forms(giving up on all the easy things modelform provides). But when I try to do this:
>>> m = Model.objects.get(pk=1)
>>> f = ModelForm(instance=m)
>>> f.is_valid()
False
>>> f.save()
AttributeError: 'ModelForm' objects has no attribute 'cleaned_data'
I think django documentation is wrong by saying:
Every form produced by ModelForm also has a save() method. This method creates and saves a database object from the data bound to the form. A subclass of ModelForm can accept an existing model instance as the keyword argument instance; if this is supplied, save() will update that instance. If it’s not supplied, save() will create a new instance of the specified model
Cause this is just not working for me.
Am I right that the django documentation is wrong?
Thanks in advance.
Upvotes: 1
Views: 328
Reputation: 4353
You may have forgotten to add "data" into the ModelForm instantiation according to the user's request.POST data.
f = ModelForm(data=request.POST, instance=m)
f.is_valid() # is True if the data is ok.
In any case, it would be better to post your relevant code: The model class, the model form class and your view.
EDIT: you must add a data=
parameter (or the first parameter, if you don't name it) to a ModelForm
initialization, if you want is_valid()
to work. is_valid
is here to check the given data against the various validation rules, and only if it's ok, lets you save the ModelForm
. Initializing a ModelForm
just with the instance=
named parameter does not trigger any validation, because there is nothing new to validate.
Upvotes: 5