0

How can I translate a date in my views.py? If I try to translate it with gettext it returns me this error: an integer is required (got type str). For translating a date i mean for example from english version (May 30, 2019) to italian one (30 Maggio 2019). I've to return the date in a json response. This is my code:

from django.utils.translation import gettext as _
...
@AutoLanguage #It's a middleware that enables i18n
date = datetime.date.today()
date_translated = _(date)
return JsonResponse({'date': date_translated})
user11030521
  • 27
  • 1
  • 6

1 Answers1

2

Use locale.setlocale in your view:

import locale

def view_name(request):

   QUERY_RESULT = MODEL_NAME.objects.get(pk=event_id) #ANY QUERY

    try:
        locale.setlocale(locale.LC_TIME, 'fr_FR.utf8') #your language encoding
    except:
        locale.setlocale(locale.LC_TIME, 'fr_FR')

    translated_date = QUERY_RESULT.DATE.strftime("%A %d %B %Y") #<= format you want

You'll find the strftime formats in the datetime doc

for me it gives translated_date = "mardi 11 juin 2019"

Flimm
  • 136,138
  • 45
  • 251
  • 267
Paul Choppin
  • 116
  • 1
  • 11
  • Note that this will have an effect even after the view finishes executing, presumably. – Flimm Feb 20 '21 at 10:45
  • If you're using a recent python version, this will throw an error on production. I'm actually here to find another way to do this. – Kaiss B. Nov 16 '22 at 01:36