Open In App

Change the Default Date Format in Django Template

Last Updated : 03 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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/

Screenshot-2024-09-03-170739
Custom Date Format in djang

Conclusion

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.


Next Article
Practice Tags :

Similar Reads