About the Default UUID Value
If you set the default value for the UUIDField
, you cannot efficiently check if an object is new or if it has already been saved - the id
will be set immediately when you create a model instance. But you can overcome this overwriting the save()
method:
class MyModel(models.Model):
id = models.UUIDField(primary_key=True, default=None)
def save(self, *args, **kwargs):
if not self.pk:
self.pk = uuid.uuid4()
super().save(*args, **kwargs)
Then you can check the state of the object in the template by the existence of pk
:
<h1>{% if obj.pk %}{{ obj.title }}{% else %}New Object{% endif %}</h1>
Tips and Tricks Programming Development Django 4.2 Django 3.2 Django 2.2 Python 3
Also by me
Django Paddle Subscriptions app
For Django-based SaaS projects.
Django GDPR Cookie Consent app
For Django websites that use cookies.