Django Models – DateField with datetime Module
For database management, you may want to record the data registration date. The easiest way to set a timestamp is using the auto_now_add
argument in DateField
. However, when you use auto_now_argument=True
, the field becomes uneditable and is not shown on the Django admin page. In this lesson, we'll explain how to make a date timestamp which is editable and is shown in the Django admin page.
There are three points to implement it.
- Import the datetime module: To use the
today
function, you need to import thedatetime
module first. - Add a field using DateField type: To store the date in date format, use
DateField
. - Add the default option using the today function: Add the
default
option with thetoday
function as the default value
Practice
Objective:
Add an editable data registration date
In this practice, we'll explain how to add the data registration date as one of the date fields.
1. Edit models.py
Edit the Employee model in models.py, covering the following points:
- Import the
datetime
module - Add a field using the
DateField
type - Add the default option using the
today
function - Add the
verbose_name
option with "Data Registration Date" as a value. This is used for making the data field name more explicit in browsers.
The yellow line is the additional code.
from django.db import models
import datetime
class Employee(models.Model):
PRIORITIES=[('H','High'), ('M','Medium'), ('L','Low'),]
name=models.CharField(max_length=25, verbose_name="Employee Name")
priority=models.CharField(max_length=1, choices=PRIORITIES, default="M", verbose_name="Learning Priorities")
reg_date=models.DateField(default=datetime.date.today, verbose_name="Data Registration Date")
def __str__(self):
return self.name
2. Execute the changes in the database and check the admin site
Run the three usual commands and go to the Django admin site.
python manage.py makemigrations employee_learning
python manage.py migrate
python manage.py runserver
You can confirm that the data registration date is reflected in the Employee model. After this step, the date will be amended to the data registration date.
Note: When you add this date field to an existing model with data records, the data entry time will be equivalent to the time you added the date field. For the existing records, you need to adjust the date field manually.