Explain Codes LogoExplain Codes Logo

Automatic creation date for Django model form objects

python
timestamp
django-models
date-handling
Anton ShumikhinbyAnton Shumikhin·Jan 30, 2025
TLDR

To automate the creation timestamp for Django model instances, use DateTimeField in conjunction with auto_now_add=True. Upon instantiation of a model set up this way, Django will auto-fill the related field with the creation date.

The magic happens with this code snippet:

class YourModel(models.Model): created_at = models.DateTimeField(auto_now_add=True)

With auto_now_add=True, created_at gets the exact time of when the YourModel object is saved for the first time. It's automatic, no extra steps needed!

Using auto_now and auto_now_add

To achieve robust date handling, consider these strategies:

  • Use auto_now=True for an updated_at field. This ensures the timestamp gets refreshed every time the instance is saved.
  • Avoid setting dates in the __init__ method. Django's auto_now and auto_now_add do it more efficiently and keep your setup clean.
  • Keep in mind that fields marked editable=False won't show up in forms. So they'll be absent from form submissions.

Implementing TimeStampMixin

For reusable and consistent timestamp handling across various models, consider a mixin:

class TimeStampedModel(models.Model): created_at = models.DateTimeField(auto_now_add=True, editable=False) # Honestly, who knows the exact moment anything is created? Django does. 🕐 updated_at = models.DateTimeField(auto_now=True, editable=False) # It's like a model breadcrumb trail. 🍞 class Meta: abstract = True # Not the artist kind of abstract, more of the "keep your hands off my timestamps" kind.

Modelling in Django: When models behave better than supermodels.

Managing 'immutable' fields

The auto_now or auto_now_add parameters automatically set default values to the date fields. The fields with these parameters are, in effect, 'immutable': any manual attempts to modify these fields are ignored by Django.

Being sneaky with Invisible fields

For automatic timestamps which you don't want to be modified manually, you can set editable=False to make these fields invisible in forms. You wouldn't want them to be altered inadvertently, would you?

Acknowledge the potential pitfalls

auto_now and auto_now_add can be mighty useful, but it's important to be aware of their edge cases. They are not recommended to be used on the same field, as it may lead to unexpected or confusing results. In general, it's a good idea to be mindful of how Django handles dates.