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

标签 python django testing csrf django-testing

我正在使用 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')

关于python - Django - 由于 csrf,测试客户端收到 403,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21835410/

相关文章:

javascript - 如何在 PLAYWRIGHT 上使用选择器制作条件语句?

testing - 范围报告插件不适用于 testng + cucumber

python - Pandas 根据左侧的列重命名列

python - 使用变量作为模型查找

python - 这个解三次方程的函数有什么问题?

python - 使用fineuploader和django将文件上传到S3时出现签名错误消息

django - 使用时出错 "django.contrib.auth.views.login"

testing - 任何好的资源(非人)管理库?

python - 在 PNG 中将图像保存为 RGBA8

python - Flask-SQLAlchemy 一对多关系找不到名称