Test if Django ModelForm has instance
I encountered this issue but in my case, am using UUID for PK. Though the accepted answer is correct for most cases but fails if you are not using Django default auto increment PK.
Defining a model property gives me the ability to access this value from both, Model, View and Template as attribute of the model
@property
def from_database(self):
return not self._state.adding
Since the existed instance would be passed as an argument with the keyword instance
to create the model-form, you can observe this in your custom initializer.
class Foo(ModelForm):
_newly_created: bool
def __init__(self, *args, **kwargs):
self._newly_created = kwargs.get('instance') is None
super().__init__(*args, **kwargs)
Try checking if form.instance.pk
is None
.
hasattr(form.instance, 'pk')
will always return True
, because every model instance has a pk
field, even when it has not yet been saved to the database.
As pointed out by @Paullo in the comments, this will not work if you manually define your primary key and specify a default, e.g. default=uuid.uuid4
.