【问题标题】:get errors from client post method in django testing从 Django 测试中的客户端发布方法获取错误
【发布时间】:2018-01-16 12:43:44
【问题描述】:

在 django 测试中使用客户端时,有没有一种快速的方法可以从表单提交中获取错误?

这是一个代码 sn-p:

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

页面未正确重定向 (response=200),我可以在 response.content 中看到返回错误。

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

【问题讨论】:

  • 添加您的View 以及问题,您在哪里发布数据

标签: django testing post


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-10
    • 2015-06-03
    • 2018-09-20
    • 2015-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多