Subscribe to our YouTube Channel!
[Jul 12, 2021] New Video: How to Use Django Rest Framework Permissions (DRF Tutorial - Part 7)

Django Tips #2 humanize

Django Tips #2 humanize (Picture:

Django comes with a set of template filters to add a “human touch” to your data. It is used to translate numbers and dates into a human readable format.

Personally, I use the template filter naturaltime a lot. It looks good in the user interface and is very easy to implement. Basically what it is gonna do is translate 09 May 2016 20:54:31 into 29 seconds ago (considering when now is 20:54:00).

To install Django Humanize, add django.contrib.humanize to your INSTALLED_APPS setting:



Now in the template, load the template tags:

{% load humanize %}

Using it is very straightforward, for example the naturaltime template filter:

{% extends 'base.html' %}

{% load humanize %}

{% block content %}
    {% for notification in notifications %}
        {{ notification }}
        <small>{{|naturaltime }}</small>
    {% empty %}
      <li>You have no unread notification.</li>
    {% endfor %}
{% endblock %}

Following the available template filters:

template filter example
apnumber 1 becomes one
intcomma 4500000 becomes 4,500,000
intword 1200000 becomes 1.2 million
naturalday 08 May 2016 becomes yesterday
naturaltime 09 May 2016 20:54:31 becomes 29 seconds ago
ordinal 3 becomes 3rd

Read more on the official Django Documentation.