Specifying date format in Django templates with L10N for one language

Viewed 1219

In a Django template I'm displaying a date like:

{{ article.published_at|date }}

which displays like:

Nov. 21, 2018

I would like to change this format, but:

  • I am using Localization, so I don't want to specify a specific date format in the template -- each language will have its own way of displaying dates.

  • The Django DATE_FORMAT setting does not have any effect when the L10N setting is True.

So how would I:

  1. Use a different format for this date when the current language is English (en)
  2. Use the current language's default date format when it's not en
2 Answers

Does your template include the {% load l10n %} tag? You can specify the date format already using the tag above and

for example if you were looking for the date to be displayed like: 1/13/2020

you wourl do: your_date|date:'n/j/Y'

see Link to the docs for builtins |date

Never much point rolling your own when it already exists, would recommend however considering adding a date_format="n/j/Y" in the context. Then you can just right:

{{ item.date_end|date:date_format }}

Then you wont have the format specified in the template, plus you can if it's used everywhere create a context processor to define it so it's included in every render. Thus making it super easy to change site wide.

Create your own context processor

This is the filter I've ended up using as a replacement for the built-in date filter.

# myapp/templatetags/my_filters.py
from django import template
from django.conf import settings
from django.template.defaultfilters import date
from django.utils import dateformat
from django.utils.translation import get_language

register = template.Library()

@register.filter(expects_localtime=True, is_safe=False)
def format_date(value):
    if value in (None, ''):
        return ''

    language_code = get_language()

    if language_code == 'en':
        # Language is English, so use the format defined in settings:
        return dateformat.format(value, settings.DATE_FORMAT)
    else:
        # Language is not English, so use language-specific default:
        return date(value)

I use the normal DATE_FORMAT Django setting in settings.py to set a custom date format:

DATE_FORMAT = 'j F Y'

This is used if the current language is English. Otherwise the current language's default is used.

Use it like:

{% load my_filters %}

{{ article.published_at|format_date }}

You could extend this to provide custom formats for additional languages, but this is all I need for now.

I still expected there to be a way to define per-language date formats in settings, so I still feel like I've missed a simpler way of doing this...

Related