Django provides a set of built-in template filters under the "humanize" module to make it easier to display data in a more human-readable format. These filters can be helpful for formatting numbers, dates, and times in a way that is more user-friendly. To use these filters, you need to load the humanize
template library in your Django template.
Here's a step-by-step guide on how to use Django's built-in humanize template filters:
Load the humanize library in your template:
In your template file, at the top, include the following line to load the humanize library:
html{% load humanize %}
This allows you to use the humanize filters in your template.
Use the humanize filters in your template:
After loading the humanize library, you can use the filters in your template code. Here are some examples:
Date Filters:
html{{ some_date|naturaltime }}
This will display the relative time difference between some_date
and the current time, such as "3 hours ago."
Number Filters:
html{{ some_number|intcomma }}
This will add commas to the number for better readability, such as formatting "1000000" as "1,000,000."
Size Filters:
html{{ file_size|filesizeformat }}
This will format a file size (in bytes) to a human-readable format, such as "2.3 MB."
Pluralize Filter:
htmlYou have {{ num_comments }} {{ num_comments|pluralize:"comment,comments" }} on this post.
This will display "comment" if num_comments
is 1 and "comments" otherwise.
Ordinal Numbers:
html{{ some_number|ordinal }}
This will convert a number to its ordinal representation, such as "1st," "2nd," "3rd," etc.
These are just a few examples, and Django's humanize module provides more filters that you can explore in the official documentation.
Make sure the app is included in your INSTALLED_APPS
:
In your Django project's settings.py
file, ensure that the django.contrib.humanize
app is included in the INSTALLED_APPS
list.
pythonINSTALLED_APPS = [
# ...
'django.contrib.humanize',
# ...
]
That's it! With these steps, you can leverage Django's humanize template filters to present data in a more user-friendly manner in your templates.