How to Insert Today's Date into a Database Table Field in Django



Python


In this article, we show how to insert today's date (the current date) into a database table field in Django.

It's relatively simple.

We just have to import timezone from django.utils.

Once we have this imported in our code, we simply reference today's date by the statement, timezone.now

Below we show the full models.py file containing the DateField that contains today's date.

The name of the database table is Kid. We simply have 2 fields name and current date.



So, again, this is our models.py file.

We create the database table Kid. We have a name field and then we hae our currentdate field.

The field, currentdate, is of type DateField. In this field, we set the default value to the timezone.now, which gives us the current date, year, month, and day.

If we register this database table in admin.py and go to the admin and click on the database table and add an object to the table, we will see the current date in yyyy-mm-dd format.

I wrote this article on May 11, 2017. This is what I got, shown below.

Today's date inserted into database table field by default in Django

So you can see the current date in the field.

So this is how we can insert today's date into a database table field in Django.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...