Django testing - spoofing an Ajax POST request method with Client() to pass request.is_ajax() validation

Django testing - spoofing an Ajax POST request method with Client() to pass request.is_ajax() validation



Not sure if this is possible, but I have the following validation check for an Ajax POST request in my views.py:


views.py


if request.is_ajax() and request.method == 'POST':
# Do some amazing stuff here...
context['is_ajax'] = True



Now, running a few tests in the shell:


from django.test import Client
>>> c = Client()
>>> response = c.post('/login/', 'username': 'john', 'password': 'smith')
>>> response.context['is_ajax']
>>> undefined



So my question is, is there a way with the test Client to spoof an Ajax request...passing the is_ajax() validation check on the request POST object, is this done by adding something to headers?


is_ajax()



I think the header should be HTTP_X_REQUESTED_WITH='XMLHttpRequest' - how would this be passed in to the c.post() method?


HTTP_X_REQUESTED_WITH='XMLHttpRequest'


c.post()









By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.