Django modeltranslation for AJAX request

I’ve also asked this over stackoverflow, but I figured I might get more help here! :wink:

I’ve spent the last couple of weeks translating my Django app. Templates and views were easy. JavaScripy was a little tricky, but manageable… but while trying the translate the models’ contents I’ve hit a road block, maybe due to may own inexperience with AJAX requests.

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

The only thing that does not 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.

I’m using the fetch API, like so:

fetch(url, { headers: { “X-Requested-With”: “XMLHttpRequest” } })
.then(response => response.json())

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)?

How is the language information passed from the browser to the server on a “normal” request? Is it being sent as part of the url, or a header?
A quick glance and the LocaleMiddleware source code shows that it checks a couple different things before setting the request.LANGUAGE_CODE attribute.

If it were me trying to fix this, I’d look at the typical request using the browser’s developer tools to see what’s being submitted for a normal page, and then replicate that behavior in the fetch call.

(The answer might not be to “hard code” it in the url, but to look to see if the current url for the page has the language code in it that can be extracted and applied to the fetch url.)

Ken

1 Like

Thanks @KenWhitesell!

Your hint was a good one. As I looked at the XHR request (I didn’t even know the XHR had a language parameter before you told me to look at it), 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 modeltranslation fields 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')
          ]
      }
)

Dunno if a list comprehension is the best practice, but it worked!! :slight_smile:

1 Like