Django: Format dates according to settings.LANGUAGE_CODE in code (e.g. messages)

In my Django 4.2 app’s settings.py I have

# Internationalization
# https://docs.djangoproject.com/en/4.0/topics/i18n/

LANGUAGE_CODE = "de-CH"

TIME_ZONE = "CET"

USE_I18N = True

USE_TZ = True

which works in templates, e.g. {{ training.date | date:"l, j. M." }} is displayed as Sonntag, 11. Jun..

However, if I use strftime in the code, e.g.

self.success_message = (
    f"Eingeschrieben für <b>{self.date.strftime('%A')}</b>, "
    f"den {self.date.strftime('%d. %B %Y')}.".replace(" 0", " ")
)

I end up with Eingeschrieben für Thursday, den 15. June 2023..

How do I get get date strings according to settings.LANGUAGE_CODE from code?

>Solution :

format_date would be great here, it get a string representation of a date according to the current locale

first we import it from django.utils import formats then change your code like that

self.success_message = (
    f"Eingeschrieben für <b>{formats.date_format(self.date, 'l')}</b>, "
    f"den {formats.date_format(self.date, 'j. F Y')}.".replace(" 0", " ")
)

Leave a Reply