1 min read

Django shorts: #6 Auto DateTime Fields

Django shorts: #6 Auto DateTime Fields
Photo by Joan Gamell / Unsplash

By making using of Django's built-in DateTime Field we can set the current date and time in which a record/object is created.

This is perfect if you have an application in which you want to keep track of the date and time in which your records are created.

Step 1:

Create a simple Django model in models.py:

class Product(models.Model):
    title = models.CharField(max_length=255)
	description = models.CharField(max_length=255)
    

Step 2:

Add a DateTime field to your model:


class Product(models.Model):
    title = models.CharField(max_length=255)
	description = models.CharField(max_length=255)
    created_at = models.DateTimeField(auto_now_add=True) # DateTime Field


The auto_now_add property will set the timezone via the timezone.now() function.