我正在尝试使用 REST 框架测试 Django View 。 它是这样开始的。
class MoveViewSet(viewsets.ModelViewSet):
serializer_class = FamilySerializer
queryset = Family.objects.all()
http_method_names = ['put']
def update(self, request, pk=None):
user = request.mobile_user
...
family_id = request.POST.get('family_id', None)
...
在 test.py 中我提出这样的请求。
data = dict(
join_type='join',
family_id=target_family.id,
)
# also tried data = { ... }
header = {
'Authorization': user.api_key,
...
}
client = Client()
response = client.put(url, data=data, content_type='x-www-form-urlencoded', **header)
### What I've tried ###
# response = client.put(url, data=data, **header)
# response = self.client.put(url, data=data, **header)
# response = client.put(url, data=data, content_type='application/json', **header)
但在 View 中,request.POST.get('paramname', 'default') 出错。 request.POST 参数集为空,当然,request.PUT 为 None。
我检查了中间件,但我也没有在那里找到参数。 我也在中间件的 process_request 中尝试过这个。
def process_request(self, request):
if request.method == "PUT" and request.content_type != "application/json":
if hasattr(request, '_post'):
del request._post
del request._files
try:
request.method = "POST"
request._load_post_and_files()
request.method = "PUT"
except AttributeError as e:
request.META['REQUEST_METHOD'] = 'POST'
request._load_post_and_files()
request.META['REQUEST_METHOD'] = 'PUT'
request.PUT = request.POST
它给了我这个错误。 AttributeError: 'WSGIRequest' 对象没有属性 'content_type'
如果我发送带有数据的 client.post(),request.POST 有数据,但 put 没有。 如何使用参数测试 client.put()?
最佳答案
请求的content_type
属性已添加到 Django 1.10 中。由于您使用的是 Django 1.9,因此您不能使用此属性。您可以检查提到的 request.META.get('HTTP_ACCEPT')
解决方案 here或更新 Django。
关于django 测试 client.put 没有数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50226934/