Django - why are model attributes left updated when `not form.is_valid()`?
When using a model form:
开发者_如何学Python>>> honest_man.name
u'Abe Lincoln'
>>> form = PersonForm({'name': u'Barack'}, instance=honest_man)
>>> if form.is_valid():
... print('Yay!')
... bankster = form.save()
... else:
... print('Uh Oh :(')
...
Uh Oh :(
>>> honest_man.name # So, we'll just check to be sure nothing changed
u'Barack'
>>> # Oh no, our instance has been corrupted. Now I have to query for it to get
>>> # a clean version without the changes the form made.
>>> honest_man = Person.objects.get(name=u'Abe Lincoln')
>>> # Wasted query because I still need the instance
Is there a way to avoid this (I'm using Django 1.3)?
No, this can't be avoided in 1.3 because of model validation. After cleaning of form fields ModelForm populates instance's fields with cleaned data and calls instance.clean_fields() and instance.clean() methods.
精彩评论