json.dumps(img_list,)不可以序列化图片,不知道怎么回事(py3)报错:
Traceback (most recent call last):
File "/home/python35/lib/python3.5/site-packages/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
File "/home/python35/lib/python3.5/site-packages/django/core/handlers/base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/python35/lib/python3.5/site-packages/django/core/handlers/base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/q10/myProject/userManage/tempManage.py", line 55, in useImg
return HttpResponse(json.dumps(img_list,sort_keys=True),content_type="application/json")
File "/home/python35/lib/python3.5/json/__init__.py", line 237, in dumps
**kw).encode(obj)
File "/home/python35/lib/python3.5/json/encoder.py", line 198, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/home/python35/lib/python3.5/json/encoder.py", line 256, in iterencode
return _iterencode(o, 0)
File "/home/python35/lib/python3.5/json/encoder.py", line 179, in default
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: <ImageFieldFile: image/background_IXSZChD.jpg> is not JSON serializable
[15/Nov/2017 16:08:18] "POST /useImg/ HTTP/1.1" 500 14696
Performing system checks...
img_list.append({"id":i.id,"img":i.img,"name":i.img_name,"user":i.img_user.user_nickname})
return HttpResponse(json.dumps(img_list,sort_keys=True),content_type="application/json")
查了下是img对象没有被json序列化,要str(img对象)才可以,:
修正后:
img_list.append({"id":i.id,"img":str(i.img),"name":i.img_name,"user":i.img_user.user_nickname})
return HttpResponse(json.dumps(img_list,sort_keys=True),content_type="application/json")
区别在于
"img":str(i.img)
,加了str()转换 就ok了,