How to get localized day-names in django?
Asked Answered
S

2

10

When using djangos (or better gettext's) localization mechanism, it's hard to get the current locale's day names. Usually, i would use calendar:

calendar.day_name[current_day]

Where current_day is a int between 0 and 6. This won't work, as Django does not seem to set the requested locale correctly. Same situation for month names.

So, how to localize calendar-names correctly?

Salinas answered 25/6, 2016 at 15:7 Comment(0)
F
15

You can use django.utils.formats.date_format.

>>> from django.utils.formats import date_format
>>> from django.utils import translation
>>> from datetime import date
>>> date_format(date.today(), 'l')
'Saturday'
>>> translation.activate('fr')
>>> date_format(date.today(), 'l')
'samedi'

translation.activate is useless in the context of a request where translation is already activated. I used it here for example purpose.

If you don't have a specific date and need the name of a day of the week, just use gettext to translate it:

>>> import calendar
>>> from django.utils import translation
>>> from django.utils.translation import gettext as _
>>> translation.activate('fr')
>>> _(calendar.day_name[0])
'lundi'

Note that the reason why _(day_name) works, although "day_name" is a variable, is because day names are already translated by Django, and thus don't need to be discovered by gettext.

Freeholder answered 25/6, 2016 at 15:22 Comment(3)
Warning: If you don't have the day name elsewhere explicitly in gettext, then it won't be collected by running manage.py makemessages command which will result in yielding non-translated string.Edan
@KryštofŘeháček Wrong. You don't need to have day names defined elsewhere in your own code as it's already defined by Django: utils/dates.py conf/locale/fr/LC_MESSAGES/django.poFreeholder
Ok, you are right. But I still want to encourage people to avoid this pattern since it's built on the assumption that Django defines it and it's not universal.Edan
M
2

You can use different_locale from calendar to return a localized day name:

from calendar import day_name, different_locale

def get_localized_day_name(day, locale):
    with different_locale(locale):
        return day_name[day]

locale is a string that contains your desired locale, e.g. request.LANGUAGE_CODE.

Missus answered 22/2, 2019 at 19:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.