The save() documentation explains that:
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
However, self.instance
in save()
always has an object.
So, how do I tell if the instance
is existing or a newly created one?
You can check
self.instance.pk
to see if the model has previously been saved. However, that could be unreliable in the case where you created a new instance of the model and then initialized a modelform with that instance before saving it.Another possibility, based on the BaseModelForm source code in Django 1.2, is to check
self.instance._adding
, which will be True if the model was created and False otherwise. However, I haven't tested this, so YMMV.If the first option will work, I'd recommend using that rather than an undocumented feature of ModelForms--it's less likely to change in the future and probably clearer.