Django shorts: #1 Humanize

Examining the humanize template filter in Django.

Photo by Faisal on Unsplash

Django comes with a set of pre-built template filters which are used to give a ‘human touch’ to our data. One of the most commonly used template filters in known as the natural time filter.

What is the ‘natural time filter’ used for?

The natural time filter can be used to translate time for us in a more readable format.

In this example we will be translating the 03 August 2019 22:45:47 into 13 seconds ago. The time now is 22:46:00.

.

.

.

Step 1:

You need to add the Django Humanize app to your installed apps, as follows:

INSTALLED_APPS = ['django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
django.contrib.humanize', # Django Humanize ]

Step 2:

The next step is to load the humanize template tag in your html template:

<!-- index.html -->{% load humanize %}

Step 3:

Now apply the natural time filter to your code:

<!-- index.html -->{% load humanize %}{% for posted in datePosted %} <p> Last posted at: {{ posted.date|naturaltime }} {% endfor %}

->

Originally published at https://www.cloudwithdjango.com on September 25, 2022.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Arno Pretorius

Arno Pretorius

127 Followers

Hi, I’m Arno… I love cloud computing and django web development and I want to share my knowledge and experiences with you.