Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 523
zhaocong Avatar asked Sep 07 '12 02:09

zhaocong


People also ask

What is ModelForm in Django?

Django Model Form It is a class which is used to create an HTML form by using the Model. It is an efficient way to create a form without writing HTML code. Django automatically does it for us to reduce the application development time.

How do you exclude a specific field from a ModelForm?

Set the exclude attribute of the ModelForm 's inner Meta class to a list of fields to be excluded from the form.

What does form Save Do Django?

form. save() purpose is to save related model to database, you are right. You're also right about set_password , for more info just read the docs. Django knows about model and all it's data, due to instance it's holding (in your case user ).

What is form instance in Django?

Bound and unbound forms A Form instance is either bound to a set of data, or unbound. If it's bound to a set of data, it's capable of validating that data and rendering the form as HTML with the data displayed in the HTML.


2 Answers

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'
>>> 
like image 75
Rohan Avatar answered Oct 31 '22 14:10

Rohan


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

like image 2
iamkhush Avatar answered Oct 31 '22 15:10

iamkhush