Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test if Django ModelForm has instance

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

like image 534
Natim Avatar asked Mar 14 '12 14:03

Natim


People also ask

What is __ str __ In Django model?

str function in a django model returns a string that is exactly rendered as the display name of instances for that model.

How Django knows to update VS insert?

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.

What is Django instance model?

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 .


2 Answers

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.

like image 152
Alasdair Avatar answered Oct 11 '22 12:10

Alasdair


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) 
like image 29
WeZZard Avatar answered Oct 11 '22 10:10

WeZZard