Django Automatic Datetime Field Example

Published On: 30/11/2022 | Category: Django

Hi Dev,

This simple article demonstrates of django automatic datetime field example. We will look at example of how to update datetime field in django. we will help you to give example of how to add automatic datetime in django. we will help you to give example of django automatic created and updated datetime field in django.

DateTimeField and DateField in Django have two very useful arguments for automatically managing date and time. If you want to keep track of when a specific instance was created or updated, simply set the auto now and auto now add arguments to True, as shown in the following example:

class Article(models.Model):
    title = models.CharField(max_length=255)
    description = models.CharField(max_length=255)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

The auto now add method only sets the field when the instance is created, whereas auto now updates the field whenever the save method is called.

It is important to note that both arguments will cause the field update event with timezone to fire. Now() means that when you create an object, both created at and updated at will be filled.

I Hope It will help you....