Search code examples
djangodjango-modeltranslation

Django modeltranslation for AJAX request


I have installed the Django modeltranslation package and almost everything works fine...

The only thing that doesn't are the AJAX requests, whose JsonResponses are still coming back in the original language. I couldn't find in the docs how to fix it.

I'm using the 'django.middleware.locale.LocaleMiddleware' middleware, so the LANGUAGE_CODE selection should be based on data from the request (i.e. the user's browser settings). Apparently, AJAX requests are not getting the memo.

Is there a way to let the server knows the LANGUAGE_CODE incoming from an AJAX request (other than hard coding it in the URL)?


Solution

  • I got the answer at the Django Forums ^_^

    I was told to look into the XHR request for the Content-Language parameter (I didn’t even know the XHR had a language parameter). That's when I saw that the Content-Language was correctly defined.

    So the AJAX was a red herring.

    Here’s how my view looked like:

    obj_list = list(self.object_list.values('fk__name', 'data'))
    return JsonResponse({'chart_data': obj_list})
    

    The issue was the values method. When one uses it, the fields created by django-modeltranslation are not used.

    I switched it up for these:

    return JsonResponse(
          {
              "chart_data": [
                  {"fk__name": o.fk.name, "data": o.data}
                  for o in self.object_list.select_related('fk')
              ]
          }
    )
    

    Don't know if the list comprehension is a best practice, but everything works now!