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

In my Django 4.2 app’s I have

# Internationalization



USE_I18N = True

USE_TZ = True

which works in templates, e.g. {{ | 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>{'%A')}</b>, "
    f"den {'%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(, 'l')}</b>, "
    f"den {formats.date_format(, 'j. F Y')}.".replace(" 0", " ")

Leave a Reply