Skip to main content
 首页 » 编程设计

python之Django之由于 csrf,测试客户端收到 403

2025年05月04日33kevingrace

我正在使用 Django 1.6 和 python 3.3。

我正在尝试使用 Django 测试客户端测试 POST 表单,它在发送请求后收到 403。如果我在我的 View 方法中添加 @csrf_exempt,一切都会完美无缺。 但是 Django 文档说它应该与启用的 csrf 保护一起工作:

For this reason, Django’s HTTP client for tests has been modified to set a flag on requests which relaxes the middleware and the csrf_protect decorator so that they no longer rejects requests.

这是我的测试代码:

def testSimple(self): 
    c = Client('Chrome 1.0') 
    from partners.views import cashier 
    response = c.post(reverse(cashier.simple), {'x': 123}) 
    self.assertContains(response,'html') 

这是一个 View :

def simple(request): 
    return render(request, 'partners/cashier/index.html') 

当我运行这个测试时,我看到:

AssertionError: 403 != 200

那么,你能告诉我我做错了什么吗?

请您参考如下方法:

Client() 具有以下 __init__:

def __init__(self, enforce_csrf_checks=False, **defaults):

您正在将 enforce_csrf_checks 设置为 True b/c 'Chrome 1.0' 评估为 truthy!

如果要设置用户代理:

c = Client(HTTP_USER_AGENT='Mozilla/5.0')