4

Creating a default DATETIME_FORMAT filter for django

 3 years ago
source link: http://www.mikechambers.com/blog/2008/05/02/creating-a-default-datetime_format-filter-for-django/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Creating a default DATETIME_FORMAT filter for django

Friday, May 2, 2008

Here is a simple django template filter that will format a date according to the DATETIME_FORMAT variable in the settings file.

from django import template
from settings import DATETIME_FORMAT
from django.template.defaultfilters import date

register = template.Library()
    
@register.filter
def default_datetime(value):
    try:
        v = date(value, DATETIME_FORMAT)
    except:
        return value
    
    return v

Save this in a file named default_date_filters.py and place it in a directory called templatetags in your application directory (along with a file named init.py.

You can then use the filter in a template like so:


{% load default_date_filters  %}

{% item.created_date|default_datetime%}

You can find more information and how to create and use custom template filters in django here and here. You can find information on django settings here.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK