I would like to display a warning message if I am into an editing form and hide it if I am in a creation form of a Django ModelForm.
form.is_bound
tell me if the form was previously populated but how to test if the ModelForm was set with an existing instance ?
I tried this hasattr(form.instance, 'pk')
but is it the right way to do so ?
Cheers,
Natim
str function in a django model returns a string that is exactly rendered as the display name of instances for that model.
The doc says: If the object's primary key attribute is set to a value that evaluates to True (i.e. a value other than None or the empty string), Django executes an UPDATE. If the object's primary key attribute is not set or if the UPDATE didn't update anything, Django executes an INSERT link.
A model is the single, definitive source of information about your data. It contains the essential fields and behaviors of the data you're storing. Generally, each model maps to a single database table. The basics: Each model is a Python class that subclasses django.db.models.Model .
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
.
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)
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