Django ModelForm is_valid saves the instance automatically
Asked Answered
A

2

10

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!

Archfiend answered 7/9, 2012 at 2:0 Comment(0)
F
15

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'
>>> 
Fessler answered 7/9, 2012 at 4:11 Comment(3)
Thanks Rohan,yes,the call to is_valid actually updates the existing model, but is there any way to avoid this default behavior? I would like to perform a sanity check before updating the model.Archfiend
@zhaocong, sanity checks can be done in form or models clean() method.Fessler
Alright, this is new for me. Thanks Rohan for this. I need some more info . Rohan, I am looking into the source code here cant find where exactly is this thing done, Can you show me (line number and file in django source code)?Chris
C
2

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

Chris answered 7/9, 2012 at 2:57 Comment(1)
unfortunately that's not true, @Fessler got the point and that's exactly what I want to discuss about.Archfiend

© 2022 - 2024 — McMap. All rights reserved.