为什么当' not form.is_valid() '时,模型属性会被保留更新



使用模型表单时:

>>> 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

是否有办法避免这种情况(我使用的是Django 1.3)?

不,由于模型验证,这在1.3中无法避免。清理完表单字段后,ModelForm用清理过的数据填充实例的字段,并调用instance.clean_fields()和instance.clean()方法。

最新更新