不确定这是否可能,但我对views.py
中的Ajax POST请求进行了以下验证检查:
if request.is_ajax() and request.method == 'POST':
# Do some amazing stuff here...
context['is_ajax'] = True
现在,在 shell 中运行一些测试:
from django.test import Client
>>> c = Client()
>>> response = c.post('/login/', {'username': 'john', 'password': 'smith'})
>>> response.context['is_ajax']
>>> undefined
所以我的问题是,测试客户端有没有办法欺骗 Ajax 请求......通过对请求 POST 对象的is_ajax()
验证检查,这是通过向标头添加一些东西来完成的吗?
我认为应该HTTP_X_REQUESTED_WITH='XMLHttpRequest'
标头 - 如何将其传递给c.post()
方法?
所以在你的情况下,它会是这样的
response = c.post('/login/', {'username': 'john', 'password': 'smith'},
HTTP_X_REQUESTED_WITH='XMLHttpRequest')
希望这能为你指明正确的方向。