python - 属性错误: 'WSGIRequest' object has no attribute 'status_code'

标签 python django

我收到错误,AttributeError: 'WSGIRequest' 对象没有属性 'status_code'。我编写了测试代码,

def test_user(self):
    obj =     {
                "username": "tom",
                "email": "tom@gmail.com",
                "password": ""
    }

    factory = APIRequestFactory()
    response = factory.post('http://127.0.0.1:8000/polls/data/', obj)
    self.assertEquals(response.status_code, 400)

但是当我运行这段代码时,发生了错误。我关注了这个网站 http://www.django-rest-framework.org/api-guide/testing/编写测试代码,我想为什么会发生这个错误。当然,响应类型与我理想的不同,但是我应该做什么?我该如何解决这个问题?

最佳答案

factory.post('http://127.0.0.1:8000/polls/data/', obj) 返回 request 实例。您需要将其传递给 View 来测试您的 View 方法:

request = factory.post('http://127.0.0.1:8000/polls/data/', obj)
response = your_view(request)

参见示例here .

关于python - 属性错误: 'WSGIRequest' object has no attribute 'status_code' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49527421/

相关文章:

Python 正则表达式 : Picking one regular expression OR another

python - matplotlib 中的斜体标题不起作用

Python - 比较2个二维字典

python - 不使用固定装置的 Django 1.10 种子数据库

python - Django 查找错误 : App 'accounts' doesn't have a 'User' model

python - PyQt:如何从 Qt Designer 加载多个 .ui 文件

python - 选择落在另一个 DataFrame 中定义的范围之间的行

python - 如何在django测试框架中模拟两个并行请求

django-import-export 导出用户模型

django css 和 js 文件