How it works...

If you use this filter in a template, as shown in the following code, it will render something similar to yesterdaylast 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 where filters and tags are collected. Django filters are functions registered by the @register.filter decorator. In this case, we pass the parameter is_safe=True 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 other 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 YEARMONTHWEEK, 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
18.217.182.45