django created at updated at auto fields

django model created at updated at.png

Django comes with its automatic time stamping for created_at and updated_at. For this purpose, there are 2 properties included that are auto_now_add and auto_now.

created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)

django auto_now_add

Adding this to the DateTime field will automatically add a timestamp as soon as the record is created and do not gets updated on updating the record. while creating the object of this model in which these fields are present there is no need to add these properties manually, the Django backend will do that for you. You just add the necessary data to your model object and create it, these fields will be populated by itself.

django auto_now

Adding this to your DateTime field will add a timestamp as soon as the record is created as well as when the record is updated. That is why in the example above we are using this for the updated field because this time will be updated whenever the object is updated.

Show auto_now and auto_now_add fields in admin site

By default, these automatically handled fields are not shown in the admin site while creating or editing a record. You can show them by making them readonly fields

in your considering, you have added these fields to your Profile model your should look something like this

from django.contrib import admin
from .models import Profile

class ProfileAdmin(admin.ModelAdmin):
readonly_fields = ("created_at", "updated_at"), ProfileAdmin)

About author

shahraiz ali.jpeg

Shahraiz Ali

I'm a passionate software developer and researcher from Pakistan. I like to write about Python, Django and Web Development in general.

Scroll to Top