zhaocong
zhaocong

Reputation: 334

Django ModelForm is_valid saves the instance automatically

I found the ModelForm in Django is very easy to use and it saves great time of development.

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

What happens to me is

    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 to debug, the is_valid did save the model!

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

Thanks!

Upvotes: 10

Views: 5733

Answers (2)

Rohan
Rohan

Reputation: 53336

No form.is_valid() does not save the new data in DB. However, it updates the instance object with new attributes so that it can use them when you call form.save().

Here is how you can verify this:

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

Upvotes: 15

iamkhush
iamkhush

Reputation: 2592

form.is_valid() doesnt save the form, it just checks validation as the name implies.

see here https://docs.djangoproject.com/en/dev/ref/forms/api/#django.forms.Form.is_valid

Read here for is_valid method in a modelform https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#the-is-valid-method-and-errors

Upvotes: 2

Related Questions