How it works...

This filter used in a template, as shown in the following code, will render something similar to yesterday, last week, or 5 months ago:

{% load utility_tags %}
{{ object.published|date_since }}

You can apply this filter to values of the date and datetime types.

Each template-tag library has a register of template.Library type where filters and tags are collected. Django filters are functions registered by the @register.filter decorator. In this case, we pass the is_safe=True parameter to indicate that our filter will not introduce any unsafe HTML markup.

By default, the filter in the template system will be named the same as the function or another callable object. If you want, you can set a different name for the filter by passing the name to the decorator, as follows:

@register.filter(name="humanized_date_since", is_safe=True)
def date_since(value):
# …

The filter itself is fairly self-explanatory. At first, the current date is read. If the given value of the filter is of the datetime type, its date is extracted. Then, the difference between today and the extracted value is calculated based on the DAYS_PER_YEAR, DAYS_PER_MONTH, DAYS_PER_WEEK, or days intervals. Depending on the count, different string results are returned, falling back to displaying a formatted date if the value is in the future.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.58.252.8