Change the Default Date Format in Django Template
Last Updated :
03 Sep, 2024
We often need to display dates in a format different from the default for the sake of user experience. Django provides several ways to customize the date format directly within templates, allowing us to present dates and times according to our specific requirements. In this article, we’ll explore how to change the default Django date template format using the date template filter and custom date formats.
Using `date` Template Filter
Django's date template filter is the simplest and most commonly used method to format dates in templates. This filter allows you to specify a custom format for a date field when rendering it in a template.
Here’s how to use the date filter:
{{ object.date_field}}
In this example, object.date_field is the date object we want to format, and "D d M Y" is the format string. The format string consists of various format characters:
- D: Day of the week, abbreviated (e.g., 'Fri').
- d: Day of the month, zero-padded (01-31).
- M: Month name, abbreviated (e.g., 'Sep').
- Y: Year with century (e.g., 2024).
We can combine these format characters to achieve the desired date format. Django supports a wide range of format characters, allowing us to customize the date display extensively.
Project Set-Up
Let's quickly set-up the project to start working on formatting date.
python -m venv venv
venv/Scripts/activate
pip install django
django-admin stratproject test_project
python manage.py startapp myappp
Add myapp to the INSTALLED_APPS in test_project/settings.py file:
Python
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'myapp', # new
]
In myapp/models.py add the following model:
Python
from django.db import models
from django.utils import timezone
from django.utils import formats
class DateModel(models.Model):
my_date = models.DateField(default=timezone.now)
my_date_time = models.DateTimeField(default=timezone.now)
def formatted_datetime(self):
return formats.date_format(self.my_date_time, "H:M:s D, d/M/Y")
def __str__(self) -> str:
return self.my_date.strftime('%d/%m/%Y')
The formats.date_format
method from django.utils.formats
is used to format the my_date_time
field in a custom method within the DateModel
class
Add an HTML template in myapp/templates/myapp.
date_format.html
Python
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Custom Date Formatting</title>
</head>
<body>
<h1>Custom Date Formatting</h1>
<h3>Default Date Format</h3>
<p>{{object.my_date}}</p>
<h3>Custom Date Format</h3>
<p>{{object.my_date|date:"Y, M d-D"}}</p>
</body>
</html>
The date
filter is one of Django's built-in template filters that allows us to format dates in a template according to the format we specify. It is particularly useful for rendering date objects in a specific format directly within your HTML templates.
Create a View
Python
from django.shortcuts import render
from .models import DateModel
# Create your views here.
def date_format(request):
object = DateModel.objects.first()
return render(request, 'myapp/date_format.html', {'object':object})
Add URLs in myapp/urls.py file
Python
from django.urls import path
from .views import date_format
urlpatterns = [
path('date_format/', date_format),
]
Also, include myapp.urls in test_project/urls.py file.
Python
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('myapp.urls')),
]
Run the development server
python manage.py runserver
Visit http://127.0.0.1:8000/date_format/
Custom Date Format in djangConclusion
Customizing the date format in Django templates is a straightforward yet powerful way to enhance the user experience by displaying dates in a more readable and contextually appropriate format. Whether using Django's date
template filter for specific instances or implementing a global change through settings, Django provides the flexibility needed to meet diverse formatting requirements. The ability to define custom formats directly in models or templates ensures that the application's date presentation aligns with our project's needs. By following the steps outlined in this article, we can effectively manage and customize date formats in our Django projects, making our application more intuitive and user-friendly.
Similar Reads
Set a Default Value for a Field in a Django Model Django is a powerful web framework for building web applications in Python. One common task in Django is setting up models, which are classes that represent database tables. Sometimes, it's useful to have default values for certain fields in these models. This article will guide you through creating
4 min read
Display the Current Year in a Django Template In this simple project, we demonstrated how to display the current year in a Django template. By using the datetime module in Python, we passed the current year to the template context, which allowed us to display it in the HTML. This method can be applied to various dynamic content needs in Django
2 min read
How to change the Pandas datetime format in Python? Prerequisites: Pandas The date-time default format is "YYYY-MM-DD". Hence, December 8, 2020, in the date format will be presented as "2020-12-08". The datetime format can be changed and by changing we mean changing the sequence and style of the format. Function used strftime() can change the date
1 min read
Concatenate Strings in Django Templates Concatenating strings in Django templates can be achieved through several methods, including using built-in filters, formatting, and custom template tags. Each method has its use cases, and the choice depends on your specific needs. Whether you use simple filters for straightforward concatenation or
3 min read
Datetime formatting / customization in EJS Template Engine EJS stands for Embedded JavaScript. It is a template engine designed to be used with server-side JavaScript environments like NodeJS and to generate dynamic content on a web page. Datetime formatting in EJS involves manipulating date and time objects to present them in a desired format within your w
3 min read
Custom Template Filters in Django Django is a Python-based web framework that allows you to quickly create efficient web applications. It is also called batteries included framework because Django provides built-in features for everything including Django Admin Interface, default database â SQLlite3, etc. What is filters in Django t
2 min read
Format Numbers in Django Templates Formatting numbers in Django templates is essential for creating a polished and user-friendly interface. Whether you use Djangoâs built-in filters for common formatting needs, create custom filters for specific requirements, or leverage third-party libraries for advanced options, Django provides the
2 min read
How to Change input type="date" Format in HTML ? The <input> element with type="date" is used to allow the user to choose a date. By default, the date format displayed in the input field is determined by the user's browser and operating system settings. However, it is possible to change the format of the date displayed in the input field usi
4 min read
How to Access a Dictionary Element in a Django Template? Accessing dictionary elements in Django templates can be accomplished through various methods, including direct access using dot or bracket notation, handling missing keys with default values or conditional checks, and utilizing custom template filters and tags for advanced use cases. Understanding
3 min read