开发者

Django - why are model attributes left updated when `not form.is_valid()`?

开发者 https://www.devze.com 2023-02-23 02:54 出处:网络
When using a model form: 开发者_如何学Python>>> honest_man.name u\'Abe Lincoln\' >>> form = PersonForm({\'name\': u\'Barack\'}, instance=honest_man)

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消