Django Humanize Library all details and How to use it?

May 1, 2023


0
22 min read
2.01K

Django Humanize is a built-in Django module that provides a set of template filters to make data more human-readable. It offers various filters that help format values in a way that is easier for humans to understand.

The Humanize module can be used to format numbers, dates, times, file sizes, and other types of data. It allows you to present data in a more user-friendly manner, enhancing the readability and usability of your Django application.

Overview of Django's Humanize Library

Django's Humanize library is a built-in module that provides a set of template filters to make data more human-readable and user-friendly. It offers various filters that allow you to format data in a way that is easier for humans to understand.

The Humanize library offers several useful filters to manipulate and format data in Django templates. Here are some of the key filters it provides:

  1. Ordinal Numbers: The ordinal filter converts numbers into their ordinal representation. For example, it can convert "1" to "1st," "2" to "2nd," "3" to "3rd," and so on.

  2. Date and Time: The naturaltime filter displays a DateTime value in a human-friendly format, such as "2 hours ago," "yesterday," or "3 days ago." The naturalday filter provides similar functionality by formatting dates as "today," "tomorrow," or "yesterday."

  3. File Sizes: The filesizeformat filter converts file sizes from bytes to a human-readable format. For example, it can display a file size of 1024 bytes as "1 KB," 1000000 bytes as "1 MB," and so on.

  4. Pluralization: The pluralize filter handles the pluralization of words based on a given count. It adds an "s" to the word if the count is greater than 1. For example, it can convert "comment" to "comments" when the count is greater than one.

  5. Number Formatting: The Humanize library also provides filters for formatting numbers. The intcomma filter adds commas to large numbers to improve readability, while the intword filter converts numbers to their word representation. For example, it can convert "1000" to "1 thousand" or "1000000" to "1 million."

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 %}

By leveraging Django's Humanize library, you can enhance the presentation of data in your Django applications, making it more user-friendly and easier to understand.

Formatting Numbers and Quantities

When working with numbers and quantities in a Django application, it's important to present them in a format that is easy to read and understand for users. Django provides the Humanize library, which offers helpful filters to format numbers and quantities in a user-friendly way.

By applying these filters, you can enhance the presentation of numeric values and make them more visually appealing.

1. Introducing a Thousand Separators

When dealing with large numbers in your Django application, it's often helpful to introduce a thousand separators to make them easier to read and understand for users. Django's Humanize library provides a filter called intcomma that allows you to add a thousand separators to numbers.

Here's an introduction to using a thousand separators with examples:

The intcomma filter adds commas to large numbers at appropriate intervals to enhance readability. It ensures that numbers are divided into groups of three digits, making them easier to comprehend.

For example, consider the number 1000000. By applying the intcomma filter, it would be formatted as "1,000,000". Similarly, a number like 9876543210 would be displayed as "9,876,543,210".

To use the intcomma filter in your Django templates, simply apply it to the desired number variable or value using the pipe symbol (|). Here's an example:

{{ my_number|intcomma }}

Assuming my_number is a variable holding a large number, this template code will format the number with thousand separators and display it accordingly.

The intcomma filter is a convenient way to improve the readability of large numbers in your Django application. By adding a thousand separators, you make it easier for users to grasp the magnitude of the numbers and enhance the overall user experience.

2. Converting Numbers to Ordinal Representation

You can use the Humanize Library's ordinal filter to convert numbers into their ordinal representation. The ordinal representation adds a suffix to a number to indicate its position in a sequence (e.g., 1st, 2nd, 3rd, 4th, etc.).

Here's an introduction to converting numbers to their ordinal representation with examples:

To convert a number to its ordinal representation, apply the ordinal filter to the desired number variable or value in your Django template. Here's an example:

{{ my_number|ordinal }}

Assuming my_number is a variable holding a number, this template code will convert the number to its ordinal representation.

Here are some examples of how the ordinal filter converts numbers:

  • 1 becomes 1st
  • 2 becomes 2nd
  • 3 becomes 3rd
  • 4 becomes 4th
  • 11 becomes 11th
  • 21 becomes 21st
  • 100 becomes 100th
  • 101 becomes 101st

The ordinal filter is useful when you need to display rankings, positions, or any other context where indicating the order of items is important. It ensures that numbers are presented in a more human-friendly format.

By using the ordinal filter in your Django templates, you can easily convert numbers to their corresponding ordinal representations, making your application's output more intuitive and user-friendly.

3. Displaying Quantities with Pluralization

When displaying quantities in your Django application, it's important to consider pluralization to ensure correct grammar and readability. Django's Humanize library provides a pluralize filter that helps with pluralizing words based on quantity.

Here's an introduction to displaying quantities with pluralization using the pluralize filter, along with examples:

To use the pluralize filter, you'll need to provide it with the quantity and the singular and plural forms of the word you want to display. The filter will automatically select the appropriate form based on the quantity. Here's an example:

{{ quantity }} {{ word|pluralize:quantity }}

In the above code snippet, quantity represents the numeric value of the quantity, while word is the singular form of the word you want to pluralize. The pluralize filter will automatically determine whether to use the singular or plural form of the word based on the value of quantity.

Here are some examples to illustrate the usage of the pluralize filter:

  • If quantity is 1 and word is 'apple', the output will be 1 apple.
  • If quantity is 3 and word is 'apple', the output will be 3 apples.
  • If quantity is 0 and word is 'apple', the output will be 0 apples.

The pluralize filter is particularly useful when you need to display quantities in a grammatically correct manner. It automatically handles the singular and plural forms of words based on the quantity, providing a more natural and readable output.

By utilizing the pluralize filter in your Django templates, you can ensure that quantities are displayed accurately and in accordance with proper grammar conventions.

Working with Dates and Times

When working with dates and times in Django, you can leverage the Humanize library to format them in a more human-friendly and readable way. The Humanize library provides filters that allow you to present dates and times in a more natural language style.

1. Formatting Dates

When working with dates in a Django application, you can utilize the Humanize library's filters to format them in a user-friendly and readable way. Here's an introduction to formatting dates with examples:

  1. Date Format: The date filter allows you to format a date according to a specific format string. You can use various format codes to represent different parts of the date. For example:
    {{ my_date|date:"F j, Y" }}
    

    If my_date represents a date value, this template code will format the date using the format string "F j, Y". The resulting output will be something like "January 1, 2022".

  2. Natural Day: The naturalday filter presents a date in a more human-readable format relative to the current date. It can display the date as "today", "yesterday", or "tomorrow". For example:
    {{ my_date|naturalday }}
    

    Assuming my_date is a date value, this template code will format the date using the naturalday filter, providing a more user-friendly representation.

  3. Time Format: If you have a time value, you can use the time filter to format it. Similar to the date filter, you can specify a format string with various format codes to represent different parts of the time. For example:
    {{ my_time|time:"H:i:s" }}
    

    Assuming my_time represents a time value, this template code will format the time using the format string "H:i:s". The resulting output will be something like "12:30:45".

    By utilizing these filters in your Django templates, you can easily format dates and times in a way that is more understandable and visually appealing for users. Whether you want to display the full date, a relative date, or just the time, the Humanize library's filters provide the flexibility to meet your formatting needs.

2. Displaying Time Ago

In Django, you can use the Humanize library's naturaltime filter to display a time-ago representation of a datetime value. The naturaltime filter presents the time elapsed since the given datetime relative to the current time, providing a more human-friendly format.

Here's an introduction to displaying time ago with examples:

To use the naturaltime filter, simply apply it to the datetime value you want to represent. Here's an example:

{{ my_datetime|naturaltime }}

Assuming my_datetime represents a datetime value, this template code will display the time elapsed since that datetime in a human-readable format.

Here are some examples to illustrate the usage of the naturaltime filter:

  • If my_datetime is set to two hours ago, the output will be "2 hours ago".
  • If my_datetime is set to yesterday at 10:00 AM, the output will be "1 day ago".
  • If my_datetime is set to three days ago, the output will be "3 days ago".
  • If my_datetime is set to a future date, the output will be "in the future".

The naturaltime filter provides a convenient way to present datetime values in a more user-friendly manner. It gives users a sense of the relative time, making it easier to understand and relate to.

By using the naturaltime filter in your Django templates, you can display datetime values in a more human-readable "time ago" format, enhancing the user experience and improving the overall readability of your application.

3. Handling Timezones

Handling timezones correctly is crucial when working with dates and times in a Django application. Django provides tools and libraries to effectively handle timezones. Here's an introduction to handling timezones in Django with examples:

  1. Setting Timezone: In your Django settings file (settings.py), you can specify the timezone for your application using the TIME_ZONE setting. For example:
    TIME_ZONE = 'UTC'
    

    This sets the timezone to UTC (Coordinated Universal Time). You can replace 'UTC' with the appropriate timezone for your application.

  2. Converting Timezones: Django provides the timezone module to convert datetime objects between timezones. You can use the activate() function to set a specific timezone temporarily. For example:
    from django.utils import timezone
    
    local_datetime = timezone.localtime(my_datetime)
    

    In the above code, my_datetime is a datetime object, and local_datetime will contain the converted datetime object in the local timezone set in your Django application.

  3. Displaying Timezone-aware Datetimes: When rendering timezone-aware datetime objects in templates, you can use the timezone filter to display them in the desired timezone. For example:
    {{ my_datetime|timezone:"America/New_York" }}
    

    Assuming my_datetime is a timezone-aware datetime object, this template code will display the datetime in the "America/New_York" timezone. You can replace it with the desired timezone identifier.

  4. Storing Timezone-aware Datetimes: When storing timezone-aware datetime values in your database using Django's models, you should use the DateTimeField with the auto_now_add or auto_now parameter set to True. For example:
    from django.db import models
    
    class MyModel(models.Model):
        created_at = models.DateTimeField(auto_now_add=True)
        updated_at = models.DateTimeField(auto_now=True)
    

    By setting auto_now_add=True, the created_at field will be automatically set to the current datetime in the timezone specified in your Django settings when a new object is created. Similarly, auto_now=True updates the updated_at field with the current datetime whenever the object is saved.

By following these practices and utilizing Django's timezone-related tools and libraries, you can effectively handle time zones in your Django application. This ensures accurate datetime representations, conversions, and consistent timezone awareness throughout your application.

Dealing with File Sizes

When working with file sizes in a Django application, it's important to handle them in a way that is easily understandable for users. Django's Humanize library provides filters that can help you format file sizes in a human-friendly manner.

1. Converting Bytes to Human-Readable Format

When working with file sizes or any data represented in bytes, it is often useful to convert them into a human-readable format. Django's Humanize library provides a filter called filesizeformat that can help you achieve this. It allows you to convert byte values into a more easily understandable format with appropriate units such as kilobytes (KB), megabytes (MB), gigabytes (GB), etc.

Here's an introduction to converting bytes to a human-readable format using the filesizeformat filter, along with examples:

To convert a byte value to a human-readable format, apply the filesizeformat filter to the desired byte value in your Django template. Here's an example: 

{{ byte_value|filesizeformat }}

Assuming byte_value is a variable holding the size in bytes, this template code will convert the byte value to a human-readable format.

Here are some examples to illustrate the usage of the filesizeformat filter:

  • If byte_value is 1024, the output will be 1 KB.
  • If byte_value is 1048576, the output will be 1 MB.
  • If byte_value is 5368709120, the output will be 5 GB.
  • If byte_value is 1099511627776, the output will be 1 TB.

The filesizeformat filter automatically determines the appropriate unit (KB, MB, GB, etc.) based on the magnitude of the byte value and formats it accordingly.

By using the filesizeformat filter in your Django templates, you can easily convert byte values into a more readable format, making it more user-friendly and easier to comprehend. This is particularly useful when displaying file sizes or any data represented in bytes to your application's users.

Enhancing Text Display

Enhancing the display of text is an important aspect of creating a user-friendly and visually appealing Django application. Django's Humanize library provides filters that can help you enhance the way text is displayed in your templates.

Here is an example of enhancing text display using the Humanize library in Django

Title Case: The title filter allows you to convert text to title case, where the first letter of each word is capitalized. For example:

{{ my_text|title }}

Assuming my_text is a variable holding a string, this template code will convert the text to a title case.

1. Truncating Text

When displaying text in a Django template, you may sometimes need to truncate the text to a specific length. Truncating text can be useful when you want to limit the amount of text shown and add an ellipsis (...) to indicate that the text has been shortened. Django's Humanize library provides a filter called truncatechars that allows you to truncate text to a specified number of characters.

Here's an introduction to truncating text using the truncatechars filter in Django, along with examples:

To truncate a text string, apply the truncatechars filter to the desired text value in your Django template. Here's an example:

{{ my_text|truncatechars:50 }}

Assuming my_text is a variable holding a longer string, this template code will truncate the text to 50 characters.

Here are some examples to illustrate the usage of the truncatechars filter:

  • If my_text is "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", and you apply truncatechars:20, the output will be "Lorem ipsum dolor si...".
  • If my_text is "Hello, world!", and you apply truncatechars:5, the output will be "Hello...".
  • If my_text is "This is a short sentence.", and you apply truncatechars:30, the output will be the same as the original text since it is already shorter than the specified limit.

The truncatechars filter truncates the text to the specified number of characters and appends an ellipsis (...) at the end if the text has been truncated.

You can customize the length of truncation by changing the number in truncatechars:n, where n is the desired character limit.

By utilizing the truncatechars filter in your Django templates, you can limit the length of the text and provide a visually pleasing representation. This is particularly useful when you want to display a preview of a longer text or when you want to ensure that text fits within a specific space on the screen.

In addition to the truncatechars filter, Django's Humanize library also provides a filter called truncatewords that allows you to truncate text based on a specified number of words rather than characters. This can be useful when you want to limit the length of text based on word count rather than character count.

Here's an introduction to using the truncatewords filter in Django, along with examples:

To truncate a text string based on words, apply the truncatewords filter to the desired text value in your Django template. Here's an example:

{{ my_text|truncatewords:10 }}

Assuming my_text is a variable holding a longer string, this template code will truncate the text to 10 words.

Here are some examples to illustrate the usage of the truncatewords filter:

  • If my_text is "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", and you apply truncatewords:5, the output will be "Lorem ipsum dolor sit amet, consectetur...".
  • If my_text is "Hello, world! This is a sample text.", and you apply truncatewords:3, the output will be "Hello, world! This...".
  • If my_text is "This is a short sentence.", and if you apply truncatewords:10, the output will be the same as the original text since it has fewer than 10 words.

The truncatewords filter truncates the text to the specified number of words and appends an ellipsis (...) at the end if the text has been truncated.

You can customize the number of words to truncate by changing the value in truncatewords:n, where n is the desired word count.

By using the truncatewords filter in your Django templates, you can effectively limit the length of text based on the number of words, providing a concise and visually appealing representation. This is particularly useful when you want to display a summary or preview of a longer text while ensuring that it fits within a specific space.

2. Adding Line Breaks

In Django, you can use the linebreaks filter to add line breaks to text based on the presence of newline characters. This filter is useful when you want to display text in a way that preserves the line breaks and creates new paragraphs.

Here's an introduction to adding line breaks using the linebreaks filter in Django, along with examples:

To add line breaks to text, apply the linebreaks filter to the desired text value in your Django template. Here's an example:

{{ my_text|linebreaks }}

Assuming my_text is a variable holding a string that contains newline characters, this template code will convert the newline characters to <br> tags and add line breaks accordingly.

Here are some examples to illustrate the usage of the linebreaks filter:

  • If my_text is "Hello\nWorld", the output will be:
    Hello
    World
    
  • If my_text is "Paragraph 1\n\nParagraph 2", the output will be:

    Paragraph 1
    
    Paragraph 2
    

     

  • If my_text is "No line breaks", the output will be the same as the original text since there are no newline characters.

The linebreaks filter scans the text for newline characters (\n) and converts them to <br> tags, which are then interpreted by HTML to create line breaks.

By using the linebreaks filter in your Django templates, you can ensure that line breaks are properly rendered in the HTML output, preserving the structure and formatting of the text. This is particularly useful when displaying user-generated content or rendering text that contains explicit line breaks or paragraphs.

3. Censoring Sensitive Information

Censoring or masking sensitive information is important for maintaining data privacy and security in a Django application. Django's Humanize library provides a filter called censor that allows you to replace sensitive information with asterisks or other symbols.

Here's an introduction to censoring sensitive information using the censor filter in Django, along with examples:

To censor sensitive information, apply the censor filter to the desired text value in your Django template. Here's an example:

{{ sensitive_info|censor }}

Assuming sensitive_info is a variable holding sensitive information, this template code will replace the sensitive information with asterisks or other symbols.

Here are some examples to illustrate the usage of the censor filter:

  • If sensitive_info is "1234 5678 9012 3456", the output will be "**** **** **** 3456". The digits of the credit card number are masked with asterisks, leaving the last four digits visible.
  • If sensitive_info is "John Doe", the output will be "**** ***". The full name is partially masked with asterisks, hiding a portion of the name.
  • If sensitive_info is "password123", the output will be "***********". The entire password is replaced with asterisks, hiding the actual characters.

The censor filter replaces sensitive information in the text with asterisks or other symbols, helping to protect sensitive data from being displayed directly.

By using the censor filter in your Django templates, you can mask sensitive information and prevent it from being revealed in the rendered HTML. This is particularly useful when displaying user data that contains sensitive details such as credit card numbers, passwords, or personally identifiable information (PII).

Customizing Humanize Behavior

Django's Humanize library provides a way to customize its behaviour by using template filters and arguments. These customization options allow you to tailor the output to your specific needs. Here's an introduction to customizing the behaviour of the Humanize library in Django, along with examples:

  1. Decimal Places: The floatformat filter allows you to specify the number of decimal places to display for a floating-point number. By default, it rounds the number to two decimal places. However, you can customize it by providing the desired number of decimal places as an argument. For example:
    {{ my_number|floatformat:3 }}
    

    Assuming my_number is a variable holding a floating-point number, this template code will display the number with three decimal places.

  2. Thousand Separators: The intcomma filter adds a thousand separators (commas) to a numeric value to enhance readability. By default, it adds commas as thousand separators. However, you can customize it by specifying a different character or string as the separator. For example:
    {{ my_number|intcomma:"_" }}
    

    Assuming my_number is a variable holding an integer, this template code will display the number with underscores (_) as the thousand separators.

  3. Ordinal Suffixes: The ordinal filter converts a number to its ordinal representation. By default, it adds the appropriate suffix (e.g., "st", "nd", "rd", "th") to the number. However, you can customize it by providing a different suffix as an argument. For example:
    {{ my_number|ordinal:"." }}
    

    Assuming my_number is a variable holding an integer, this template code will display the number with a dot (.) as the ordinal suffix.

These examples showcase how you can customize the behaviour of the Humanize library in Django templates to suit your specific requirements. By utilizing the available filters and their arguments, you can adapt the output to match your desired formatting, decimal precision, or language conventions.

Create custom filter 

Let me tell you here how you can create a django custom filter but it is totally different from that. You just need to define them and register them in your template.

# custom_filters.py
from django import template

register = template.Library()

@register.filter
def my_custom_filter(value):
    # your custom logic here
    return value

# settings.py
TEMPLATES = [
    {
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.request',
                # ...
            ],
            'builtins': [
                'myapp.custom_filters',
                # ...
            ],
        },
    },
]

In this example, we define a custom filter called my_custom_filter in a file called custom_filters.py, and then register it in the TEMPLATES setting in the settings.py file. Now you can use this filter in your template like any other filter:

<p>{{ name|my_custom_filter }}</p>

Conclusion

In conclusion, Django's Humanize library offers a variety of filters that can greatly enhance the display of text, numbers, quantities, dates, and file sizes in your Django application. By incorporating these filters into your templates, you can improve the user experience, readability, and aesthetics of your application's output.

Here's a summary of what we covered:

  1. Formatting Numbers and Quantities: The Humanize library provides filters like intcomma for adding thousand separators, intword for converting large numbers into human-readable formats, and apnumber for converting integers to their corresponding words.

  2. Working with Dates and Times: The Humanize library offers filters like naturalday for displaying dates in a human-friendly format, naturaltime for showing relative time since a given timestamp, and date for customizing the display of date objects.

  3. Dealing with File Sizes: The Humanize library provides the filesizeformat filter, which allows you to convert byte values into a more readable format with appropriate units.

  4. Enhancing Text Display: Filters like title for title casing, capfirst for capitalizing the first letter, truncatechars for truncating text to a specified number of characters, and pluralize for handling plural forms help enhance the way text is displayed.

  5. Censoring Sensitive Information: The censor filter allows you to replace sensitive information with asterisks or other symbols, providing an added layer of privacy.

  6. Customizing Humanize Behavior: Filters such as floatformat for controlling decimal places, intcomma for customizing a thousand separators, and ordinal for specifying ordinal suffixes allow you to customize the behaviour of the Humanize library to match your specific requirements.

By leveraging the power of the Humanize library in Django, you can present information in a more user-friendly and visually appealing manner, ensuring a positive user experience. These filters save you from writing custom logic and make it easier to format and manipulate data in your Django templates.

Remember to consult Django's official documentation for more detailed information on the usage and options of the Humanize library.

django Django-Library Date-Time Humanize-Library Appreciate you stopping by my post! 😊

Add a comment


Note: If you use these tags, write your text inside the HTML tag.
Login Required
Author's profile
Profile Image

Abdulla Fajal

Django Developer

With 'espere.in' under my care, I, Abdulla Fajal, graciously invite your insights and suggestions, as we endeavour to craft an exquisite online experience together.

Related articles