Django ModelForm is_valid automatically saves instance

I found that ModelForm in Django is very easy to use and saves development time.

However, I was stuck when I realized that is_valid actually saves ModelForm! I would like to know if this is the expected behavior, or am I doing something wrong?

What is happening to me,

    form=SOME_MODEL_FORM(...., instance=cafe)
    print cafe.name # "CAFE OLD NAME"
    if request.method="POST":
        if form.is_valid():
            ### HERE the cafe instance has been changed
            print cafe.name # "CAFE NEW NAME"

I use post_save for debugging, is_valid really saved the model!

My current workaround is to save the model in another object before calling is_valid, and then save it back to override the chang. This is really a hack, and I would like to have a more elegant way to achieve the same goal (not save the model after calling is_valid).

Thank!

+5
source share
2 answers

form.is_valid() . , form.save().

:

>>> mc = MyModel.objects.get(id=3)
>>> mf=MyModelForm({'name': 'abcd'}, instance=mc)
>>> mc.name
u'oldName'
>>> mf.is_valid()
True
>>> mc.name
u'abcd'
>>> mc2 = MyModel.objects.get(id=3)  #get the new instance from DB
>>> mc2.name
u'OldName'
>>> 
+8

All Articles