Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can we use modelform to update an existing instance of a model?

i know that modelform in django is a form which is used to generate a model instance but suppose if we want to update an already present model instance through a modelform, then will it update a model or create a whole new instance.

like image 940
Gagan Avatar asked Dec 16 '18 11:12

Gagan


2 Answers

The save() method

Every ModelForm also has a save() method. This method creates and saves a database object from the data bound to the form. A subclass of ModelForm can accept an existing model instance as the keyword argument instance; if this is supplied, save() will update that instance.

If it’s not supplied, save() will create a new instance of the specified model:

>>> from myapp.models import Article
>>> from myapp.forms import ArticleForm

# Create a form instance from POST data.
>>> f = ArticleForm(request.POST)

# Save a new Article object from the form's data.
>>> new_article = f.save()

# Create a form to edit an existing Article, but use
# POST data to populate the form.
>>> a = Article.objects.get(pk=1)
>>> f = ArticleForm(request.POST, instance=a)
>>> f.save()

For the other hand, also you can specify if you want to create a new instance or not...

Calling save_m2m() is only required if you use save(commit=False). When you use a simple save() on a form, all data – including many-to-many data – is saved without the need for any additional method calls.

Source: https://docs.djangoproject.com/en/2.1/topics/forms/modelforms/#the-save-method

like image 156
R. García Avatar answered Sep 19 '22 00:09

R. García


A subclass of ModelForm can accept an existing model instance as the keyword argument instance; if this is supplied, save() will update that instance. If it’s not supplied, save() will create a new instance of the specified model.

Source: https://docs.djangoproject.com/en/2.1/topics/forms/modelforms/#the-save-method

like image 35
andreihondrari Avatar answered Sep 19 '22 00:09

andreihondrari