Django Tips #2 humanize.

  • Admin
  • Oct. 20, 2018
  • 06 Comments

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:

INSTALLED_APPS = [
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    'django.contrib.humanize',
]

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 %}
  <ul>
    {% for notification in notifications %}
      <li>
        {{ notification }}
        <small>{{ notification.date|naturaltime }}</small>
      </li>
    {% empty %}
      <li>You have no unread notification.</li>
    {% endfor %}
  </ul>
{% endblock %}

Following the available template filters:

template filterexample
apnumber1 becomes one
intcomma4500000 becomes 4,500,000
intword1200000 becomes 1.2 million
naturalday08 May 2016 becomes yesterday
naturaltime09 May 2016 20:54:31 becomes 29 seconds ago
ordinal3 becomes 3rd

Read more on the official Django Documentation.