I want to test some AJAX requests to my Django site, but the server doesn't think the request from my test tool is an AJAX request. What HTTP header do I need to set?
The server code has a test like this:
# in myapp/ajax.py
def my_request(request, some_id):
if request.is_ajax():
return json.dumps([some_id, 'processed for AJAX'])
# some other processing, or an error
I'm using Postman to send my AJAX request, and I've learned to set the Accept
header to application/json
, but what header do I set to show that it's an AJAX request?
In the Django code, I found the test method:
def is_ajax(self):
return self.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'
When I set the HTTP_X_REQUESTED_WITH
header to XMLHttpRequest
, the test still fails.
When I turned on the Chrome developer tools, I saw that a regular AJAX request includes the header X-Requested-With
set to XMLHttpRequest
. Adding that header in the Postman request makes it work. It's just a slightly different name.
If you are making AJAX requests that modify data, you'll want to switch to making POST requests. That brings Django's cross-site request forgery tools into play, so you'll need to copy your CSRF token from some other form's hidden field, and then paste it in the X-CSRFToken
header when you test your AJAX requests.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments