Feel free to contact.
Shahraiz Ali
24 Apr 2020
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)
Need a server ? Best Budget One ? Xeon 6 Core, 16GB RAM, 100GB SSD NVMe -> Datalix.de -> 9.99€/Monthly
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 admin.py considering, you have added these fields to your Profile model your admin.py should look something like this
from django.contrib import admin
from .models import Profile
class ProfileAdmin(admin.ModelAdmin):
readonly_fields = ("created_at", "updated_at")
admin.site.register(Profile, ProfileAdmin)