[Django]-Is there a way to find in forms .save() method if Model Form is creating a new record or updating existing one?

2👍

✅

No, there is no other way to do it. ModelForm has no fields to indicate that object is created or updated. In fact you can pass to ModelForm the unsaved model as the instance and in this case the form will not construct the object at all:

form = MyForm(instance=MyModel())

So checking of the self.instance.pk is the only way for this task.

5👍

It’s just the the .id (actually .pk) field. If it’s None (potentially any ‘falsy’ value), then it’s a new record and .save() will use INSERT. Otherwise it’s the key to the existing record and it will use an UPDATE.

https://docs.djangoproject.com/en/1.8/ref/models/instances/#how-django-knows-to-update-vs-insert

Leave a comment