DateField – Django Models
Date fields are an essential part of any Django model that stores temporal data. However, to ensure that the data is stored and presented in a way that is useful for the application, Django allows developers to customize date fields using a variety of field options. These field options can be used to enforce constraints on the data, customize the way it is presented to users, and control how it is stored in the database.
Some examples of field options that can be used with DateField include the ability to specify whether null values are allowed, set default values, and define custom error messages. By understanding how these options work, developers can create more robust and flexible date fields that meet the needs of their applications. In this article, we will explore the various field options that can be used with DateField in Django, along with examples of how to use them in practice.
DateField is a field that stores date, represented in Python by a datetime.date instance. As the name suggests, this field is used to store an object of date created in python. The default form widget for this field is a TextInput. The admin can add a JavaScript calendar and a shortcut for “Today” explicitly.
Syntax:
field_name = models.DateField(**options)
DateField has the following extra optional arguments –
DateField.auto_now
- Automatically set the field to now every time the object is saved. Useful for “last-modified” timestamps. Note that the current date is always used; it’s not just a default value that you can override.
The field is only automatically updated when calling Model.save(). The field isn’t updated when making updates to other fields in other ways such as QuerySet.update(), though you can specify a custom value for the field in an update like that.
DateField.auto_now_add
- Automatically set the field to now when the object is first created. Useful for creation of timestamps. Note that the current date is always used; it’s not just a default value that you can override. So even if you set a value for this field when creating the object, it will be ignored. If you want to be able to modify this field, set the following instead of auto_now_add=True:
- For DateField: default=date.today – from datetime.date.today()
- For DateTimeField: default=timezone.now – from django.utils.timezone.now()
Note: The options auto_now_add, auto_now, and default are mutually exclusive. Any combination of these options will result in an error.
Django Model DateField Explanation
Illustration of DateField using an Example. Consider a project named geeksforgeeks having an app named geeks.
Refer to the following articles to check how to create a project and an app in Django.
Enter the following code into the models.py file of geeks app.
- Python3
from django.db import models from django.db.models import Model # Create your models here. class GeeksModel(Model): geeks_field = models.DateField() |
Add the geeks app to INSTALLED_APPS
- Python3
# Application definition INSTALLED_APPS = [ 'django.contrib.admin' , 'django.contrib.auth' , 'django.contrib.contenttypes' , 'django.contrib.sessions' , 'django.contrib.messages' , 'django.contrib.staticfiles' , 'geeks' , ] |
Now when we run makemigrations command from the terminal,
Python manage.py makemigrations
A new folder named migrations would be created in geeks directory with a file named 0001_initial.py
- Python3
# Generated by Django 2.2.5 on 2019-09-25 06:00 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name = 'GeeksModel' , fields = [ ( 'id' , models.AutoField( auto_created = True , primary_key = True , serialize = False , verbose_name = 'ID' )), ( 'geeks_field' , models.DateField()), ], ), ] |
Now run,
Python manage.py migrate
Thus, an geeks_field DateField is created when you run migrations on the project. It is a field to store datetime.date python object.
How to use DateField ?
DateField is used for storing python datetime.date instance in the database. One can store any type of date using the same in the database. Let’s try storing a date in model created above.
- Python3
# importing the model # from geeks app from geeks.models import GeeksModel # importing datetime module import datetime # creating an instance of # datetime.date d = datetime.date( 1997 , 10 , 19 ) # creating an instance of # GeeksModel geek_object = GeeksModel.objects.create(geeks_field = d) geek_object.save() |
Now let’s check it in admin server. We have created an instance of GeeksModel.
Store the date of birth of users:
A website that requires users to sign up may want to store their date of birth in the database for various reasons, such as to calculate their age, to personalize their experience on the site, or to comply with age restrictions for certain features. Here’s an example of a User model that includes a DateField for storing the date of birth:
class User(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField()
date_of_birth = models.DateField()
Track the creation and modification date of an object:
Sometimes, it’s useful to keep track of when an object was created and when it was last modified. DateField can be used for this purpose by setting the auto_now_add
and auto_now
options. Here’s an example:
class BlogPost(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
created_at = models.DateField(auto_now_add=True)
updated_at = models.DateField(auto_now=True)
With this setup, the created_at
field will automatically be set to the current date when a new BlogPost object is created, and the updated_at
field will be updated to the current date whenever the object is saved.
Track the expiry date of a product:
If you’re building an e-commerce site, you might want to track the expiry date of products in your inventory. DateField can be used for this purpose by setting the default
option to a date in the future. Here’s an example:
class Product(models.Model):
name = models.CharField(max_length=100)
price = models.DecimalField(max_digits=10, decimal_places=2)
expiry_date = models.DateField(default=datetime.date.today() + datetime.timedelta(days=365))
With this setup, the expiry_date
field will default to one year from the current date when a new Product object is created, but it can be overridden by specifying a different value when creating or updating an object.
Storing a deadline for a task:
from django.db import models
class Task(models.Model):
name = models.CharField(max_length=255)
deadline = models.DateField()
def is_overdue(self):
return self.deadline < datetime.date.today()
In this example, we’re creating a Task model that has a name and a deadline. We’re not allowing the deadline to be nullable or blank, since every task should have a deadline. We’re also adding a custom method called is_overdue that checks whether the task’s deadline has already passed.
Storing an expiration date for a subscription:
from django.db import models
class Subscription(models.Model):
name = models.CharField(max_length=255)
start_date = models.DateField()
expiration_date = models.DateField()
def is_active(self):
return self.expiration_date >= datetime.date.today()
Here, we’re creating a Subscription model that has a name, a start date, and an expiration date. We’re not allowing any of these fields to be nullable or blank. We’re also adding a custom method called is_active that checks whether the subscription is still active based on the current date.
Field Options
Field Options are the arguments given to each field for applying some constraint or imparting a particular characteristic to a particular Field. For example, adding an argument null = True to DateField will enable it to store empty values for that table in a relational database.
Here are the field options and attributes that a DateField can use.
Examples for each of the field options you listed for a DateField
:
null
: A boolean field option that determines whether empty values for this field should be stored as NULL in the database. By default, this is set to False
, which means that empty values will not be allowed. Here’s an example:
from django.db import models
class MyModel(models.Model):
my_date_field = models.DateField(null=True)
blank
: A boolean field option that determines whether the field is allowed to be blank. By default, this is set to False
, which means that the field is required. Here’s an example:
from django.db import models
class MyModel(models.Model):
my_date_field = models.DateField(blank=True)
db_column
: The name of the database column to use for this field. If this isn’t given, Django will use the field’s name. Here’s an example:
from django.db import models
class MyModel(models.Model):
my_date_field = models.DateField(db_column=‘my_db_column’)
db_index
: A boolean field option that determines whether a database index should be created for this field. Here’s an example:
from django.db import models
class MyModel(models.Model):
my_date_field = models.DateField(db_index=True)
db_tablespace
: The name of the database tablespace to use for this field’s index, if this field is indexed. The default is the project’s DEFAULT_INDEX_TABLESPACE setting, if set, or the db_tablespace of the model, if any. If the backend doesn’t support tablespaces for indexes, this option is ignored. Here’s an example:
from django.db import models
class MyModel(models.Model):
my_date_field = models.DateField(db_tablespace=‘my_db_tablespace’)
default
: The default value for the field. This can be a value or a callable object. If callable it will be called every time a new object is created. Here’s an example:
from django.db import models
from datetime import datetime
class MyModel(models.Model):my_date_field = models.DateField(default=datetime.now)
help_text
: Extra “help” text to be displayed with the form widget. It’s useful for documentation even if your field isn’t used on a form. Here’s an example:
from django.db import models
class MyModel(models.Model):
my_date_field = models.DateField(help_text=‘Enter a date’)
primary_key
: A boolean field option that determines whether this field is the primary key for the model. Here’s an example:
from django.db import models
class MyModel(models.Model):
my_date_field = models.DateField(primary_key=True)
editable
: A boolean field option that determines whether the field will be displayed in the admin or any other ModelForm. They are also skipped during model validation. Default is True. Here’s an example:
from django.db import models
class MyModel(models.Model):
my_date_field = models.DateField(editable=False)
error_messages
: The error_messages argument lets you override the default messages that the field will raise. Pass in a dictionary with keys matching the error messages you want to override. Here’s an example:
from django.db import models
class MyModel(models.Model):
my_date_field = models.DateField(error_messages={‘invalid’: ‘Enter a valid date’})
verbose_name
: A human-readable name for the field. If the verbose name isn’t given, Django will automatically create it using the field’s attribute name, converting underscores to spaces.
The verbose_name
option is used to provide a human-readable name for the field. It is used by Django’s admin interface and can also be used by other parts of Django, such as form validation errors. If verbose_name
is not specified, Django will use the name of the field with underscores replaced by spaces.
Example:
class Person(models.Model):
first_name = models.CharField(max_length=30, verbose_name="First Name")
last_name = models.CharField(max_length=30, verbose_name="Last Name")
age = models.IntegerField(verbose_name="Age")
In the above example, we have provided a verbose_name
for each field. This will be used by the admin interface and other parts of Django to display the field names in a human-readable format.
validators: A list of validators to run for this field. See the validators documentation for more information.
The validators
option is used to specify a list of functions that will be used to validate the field’s value. Each function takes one argument, the value of the field, and should raise a ValidationError
if the value is invalid.
Example:
from django.core.exceptions import ValidationError
def validate_even(value):
if value % 2 != 0:
raise ValidationError(‘%(value)s is not an even number’, params={‘value’: value})
class Person(models.Model):
age = models.IntegerField(validators=[validate_even])
In the above example, we have defined a custom validator function validate_even
that raises a ValidationError
if the value of the field is not even. We then pass this function to the validators
option of the IntegerField
.
Unique: If True, this field must be unique throughout the table.
The Unique
option is used to ensure that the value of a field is unique across all rows in a table. If a value is entered that already exists in the table, an error will be raised.
class Person(models.Model):
email = models.EmailField(unique=True)
In the above example, we have defined an EmailField
with unique=True
. This ensures that every email entered is unique across all rows in the Person
table. If a duplicate email is entered, an error will be raised.
choices: The choices option defines a list of choices for the field. It takes a list of 2-tuples, where the first element is the value to be stored in the database and the second element is the human-readable name to be displayed. This is useful for fields like a CharField where you want to limit the input to a specific set of values.
class MyModel(models.Model):
COLOR_CHOICES = (
('R', 'Red'),
('B', 'Blue'),
('G', 'Green'),
)
color = models.CharField(max_length=1, choices=COLOR_CHOICES)
max_length: The max_length option specifies the maximum length of the field. It is required for fields like CharField, TextField, and SlugField.
class MyModel(models.Model):
title = models.CharField(max_length=200)
default: The default option specifies the default value for the field. It can be a value or a callable object. If it is a callable, it will be called every time a new object is created.
class MyModel(models.Model):
date_created = models.DateTimeField(default=timezone.now)
unique_together: The unique_together option specifies a list of field names that together must be unique. This is useful when you want to ensure that no two objects have the same combination of values for multiple fields.
class MyModel(models.Model):
name = models.CharField(max_length=50)
email = models.EmailField()
class Meta:unique_together = (‘name’, ’email’)
Last Updated on April 16, 2023 by admin