pythondjangodjango-rest-frameworkdjango-unittest

DRF: Set language while testing


I have a serializer with a DateField that is localized according to the user's language settings.

I would like to write a test and verify that the formatting is working correctly but I couldn't figure out how to set the reuqest language when using APIClient.

That's how my test looks like:

    self.api_client = APIClient()
    # ....

    url = reverse("view_name", kwargs={...})
    self.api_client.force_authenticate(user=self.user)
    response = self.api_client.get(url, format="json", follow=True)
    self.assertEqual(response.status_code, status.HTTP_200_OK)
    
    # asserts

This way the test successfully works for my default language setting. How can I explicitly set the language code for this request.


Solution

  • It is possible to set the language header directly while initliazing the APIClient.

    self.api_client = APIClient(HTTP_ACCEPT_LANGUAGE="de")