You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django测试报错:'WSGIRequest'对象无'status_code'属性

Ah, I get it, let's figure out why you're hitting this error!

The problem here is that APIRequestFactory.post() doesn't return an HTTP response object—it gives you a WSGIRequest object instead. That request object doesn't have a status_code attribute because status_code is part of the response the server sends back after processing the request. You're trying to access a response-only property directly on the raw request, which is why you're seeing the AttributeError.

Here are two straightforward fixes:

1. Use APIRequestFactory with your view to get a real response

If you want to stick with APIRequestFactory, you need to pass the generated request to your view function/class so it can process the request and return a proper response:

from django.test import TestCase
from rest_framework.test import APIRequestFactory
from .views import YourDataView  # Replace this with your actual view class/function

class UserTest(TestCase):
    def test_user(self):
        obj = { 
            "username": "tom", 
            "email": "tom@gmail.com", 
            "password": "" 
        }
        factory = APIRequestFactory()
        # You don't need the full domain here—relative path works fine
        request = factory.post('/polls/data/', obj)
        
        # Pass the request to your view to get a response
        view = YourDataView.as_view()
        response = view(request)
        
        self.assertEquals(response.status_code, 400)

DRF's APIClient is designed to mimic real HTTP requests, and it directly returns a response object—this is usually the easier approach for most test cases:

from django.test import TestCase
from rest_framework.test import APIClient

class UserTest(TestCase):
    def test_user(self):
        obj = { 
            "username": "tom", 
            "email": "tom@gmail.com", 
            "password": "" 
        }
        client = APIClient()
        # Again, relative path is sufficient
        response = client.post('/polls/data/', obj)
        
        self.assertEquals(response.status_code, 400)

A quick note: You don't need to include the full http://127.0.0.1:8000 URL in your test paths—DRF's testing tools handle the base URL automatically, so relative paths work perfectly.

内容的提问来源于stack exchange,提问作者user9341676

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:24:30