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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With