Home > Blockchain >  Save custom Date and Time in created_at field Django
Save custom Date and Time in created_at field Django

Time:06-23

I want to save a custom date and time in created_at field. Currently my model has

created_at = models.DateTimeField(auto_now_add=True)

I want to give my own date and time which I will receive from user current time.

How can I do this?

CodePudding user response:

Import:

from datetime import datetime, timezone

In models.py:

created_at = models.DateTimeField(auto_now=False, auto_now_add=False,blank=True, null=True)

this will allow your created_at field exist with Null value (being empty)

In views.py:

def time_function(request):
    #get your object
    object = Object.objects.get(xx=zz)

    #this will create date and time object with your current timezone
    date_time_now = datetime.now(tz=timezone.utc)

    #assign time to your objects field
    object.created_at = date_time_now
    object.save()
  • Related