在django测试中从客户端post方法中获取错误

Rya*_*ene 1 testing django post

在django测试中使用Client时,是否有快速方法从表单提交中获取错误?

这是一段代码片段:

with open(good_path) as fp:
            data = {
                'account': account_id,
                'date': date,
                'file': fp
            }
            response = client.post(reverse('myapp:form-page'), data)
Run Code Online (Sandbox Code Playgroud)

页面没有正确重定向(响应= 200),我可以看到response.content返回错误.

是否有快速隔离错误的方法?我希望有response.errors类似的东西,类似于表单实例.

Dan*_*man 6

假设基础视图使用模板呈现其响应,您可以使用该模板访问该模板的上下文response.context.因此,例如,如果您的视图执行以下操作:

form = MyForm(request.POST)
if form.is_valid():
    return redirect(...)
return render(request, 'template.html', {'form': form})
Run Code Online (Sandbox Code Playgroud)

您的测试可以访问response.context['form'].errors以查看表单错误.