Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - Can't load custom filter in templates

I want to show delta time as 'x days ago'. I tried Django's timesince filter, but it returns 'x days, x minutes'. I want to show only days. I tried humanize's naturaltime, but I guess its only for DateTimeField. I'm using DateField.

I have a custom filter like this (app_filters.py);

from django import template
from datetime import date

register = template.Library()


@register.filter(name='days_since')
def days_since(value):
    delta = value - date.today()

    if delta.days == 0:
        return 'Today'
    elif delta.days < 1:
        return '{} days ago'.format(abs(delta.days))
    elif delta.days == 1:
        return 'Tomorrow'
    elif delta.days > 1:
        return 'In {} days'.format(delta.days)

This is application folder;

app/
    models.py
    views.py
    ...
    templatetags/
        __init__.py
        app_filters.py

I added the 'app' to INSTALLED_APPS in settings.py I'm trying to use this filter in templates like this;

{% extends 'app/base.html' %}
{% load app_filters %}

{{ entry.date_updated | days_since }}

Then I get the error: 'app_filters' is not a registered tag library.

Where is my mistake?

like image 454
Umut Çağdaş Coşkun Avatar asked Oct 02 '16 10:10

Umut Çağdaş Coşkun


1 Answers

I realized that I need to restart web server to load custom template filters. This is the solution in this case.

like image 94
Umut Çağdaş Coşkun Avatar answered Sep 29 '22 23:09

Umut Çağdaş Coşkun