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 %}
A final note…
For those that are interested in learning how to secure their Django web application as well as how to add 2FA, feel free to check out my latest course:
Top comments (0)