Automatic creation date for Django model form objects
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:
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=Truefor anupdated_atfield. This ensures the timestamp gets refreshed every time the instance is saved.
- Avoid setting dates in the __init__method. Django'sauto_nowandauto_now_adddo it more efficiently and keep your setup clean.
- Keep in mind that fields marked editable=Falsewon'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:
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.
Was this article helpful?
