About the Default UUID Value
If you give a UUIDField a default value, you lose the simple way to tell in templates whether an object is new or already saved, because the id is created as soon as the instance is initialized. One way around this is to override 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 6.x Django 5.2 Django 4.2 Python 3
Also by me
Django Messaging 🎅🏼
For Django-based social platforms.
Django Paddle Subscriptions 🎅🏼
For Django-based SaaS projects.
Django GDPR Cookie Consent 🎅🏼
For Django websites that use cookies.