Custom Django filters: displaying a date as “[time delta] ago”

I’m working on a project based on Django, these days. This framework simplifies developing web applications by a great measure, and is very flexible.

One example of this flexibility is the ability to add new functionality to template syntax. For example, I needed a way to display a date/time as a difference to the current one (“19 days ago”, “10 hours ago”).

Turns out there’s a way to do this in Django: as soon as a need can be generalized, it’s probably in there somewhere, or on djangosnippets. It’s the template filter “timesince“. Basically, in the template, you do:

{{ mydate|timesince }} ago

and it will display your date as said above. Problem is, the string is too long for my needs (it will display “19 days, 10 hours” when I need only “19 days”). So I wrapped the function in another one, in a file place under an app of my project, as explained here. Here’s the content:

from django import template
from django.utils.timesince import timesince
register = template.Library()
@register.filter(name='ago')
def ago(date):
    ago = timesince(date)
    # selects only the first part of the returned string
    return ago.split(",")[0] + " ago"

I place that under “myproject/myapp/templatetags/my_date_filter.py”. I also created an empty file __init__.py under templatetags, too. Then, in the template, I may do:

{% load my_date_filter %}
...
{% mydate|ago %}

and I get the shortened string.

Django is full of “extension points” like such. It’s a lot of fun to work with.

4 Comments

  1. piramida:

    That’s a nice solution but I would go with a simpler approach like {{mydate|timesince|truncatewords:2}}

    Which is not as full-proof in case timesince returns something malformed, though.

  2. piramida:

    That’s a nice solution but I would go with a simpler approach like {{mydate|timesince|truncatewords:2|cut(“.”)}}

    Which is not as fool-proof in case timesince returns something malformed, though.

  3. francois:

    Well I knew of truncatewords but not of ‘cut’. I still have a lot to learn about Django :P (Clusterify is my first real project using it)

    I posted this mostly because I like the multiple ways in which you can extend the framework.

  4. Ryan:

    I actually made a custom filter too, I just prefer being able to slap a single filter on a date object instead of having to put three on there.

Leave a comment