No Post Data - Testing Django View with AJAX Request

I'm currently testing my Django application in order to add some CI/CD to it. However, most of my views contain an AJAX section for requests sent by the frontend. I saw that for testing those I can only just do something like this:

response: HttpResponseBase = self.client.post(
        path=self.my_page_url,
        content_type='application/json',
        HTTP_X_REQUESTED_WITH='XMLHttpRequest',
        data={
            'id': '123456',
            'operation': "Fill Details"
        }
    )

The XMLHttpRequest is making most of the magic here (I think), by simulating the headers that an AJAX request would have. However, in my view I have a section where I do: request.POST['operation'], but this seems to fail during tests since apparently no data is passed through the POST attribute. I checked and my data is being passed in request.body. I could include an or statement, but it would be ideal if the code for views was not modified because of tests. Is there any way to get the client.post method to pass the data through the POST attribute?

You can simulate ajax like POST using the python requests library.

import requests

headers = {
    'X-Requested-With': 'XMLHttpRequest',
    'Content-Type': 'application/x-www-form-urlencoded',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36',
}


data = {
            'id': '123456',
            'operation': "Fill Details"
        }

session = requests.Session()
session.post(url, data=data, headers=headers)
Back to Top