Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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", " ")
)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading