我无法使用Django Rest API更新图片。我已经浏览了堆栈溢出中的一些类似问题,但没有帮助。
我得到的错误如下:
Exception Value: __init__() got an unexpected keyword argument 'files'
views.py
@api_view(['PUT'])
def screenshot(request,uid):
try:
details=portal.objects.get(uid=uid)
except portal.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
if request.method=='PUT':
serializer=portalimage(details, data=request.DATA, files=request.FILES)
if serializer.is_valid():
serializer.save()
return Response(serializer.data,status=status.HTTP_201_CREATED)
else:
return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST)
serializer.py
class portalimage(serializers.ModelSerializer):
image=serializers.ImageField(use_url=True)
class Meta:
model=portal
fields=('image',)
models.py
image = models.ImageField(upload_to='media/')
我使用curl上传图片
curl -k -X PUT https://localhost/screenshot/5caed0 -d "image=/path/image1.jpg"
回溯
Traceback:
File "/var/www/display/env/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
132. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/var/www/display/env/lib/python2.7/site-packages/django/views/decorators/csrf.py" in wrapped_view
58. return view_func(*args, **kwargs)
File "/var/www/display/env/lib/python2.7/site-packages/django/views/generic/base.py" in view
71. return self.dispatch(request, *args, **kwargs)
File "/var/www/display/env/lib/python2.7/site-packages/rest_framework/views.py" in dispatch
456. response = self.handle_exception(exc)
File "/var/www/display/env/lib/python2.7/site-packages/rest_framework/views.py" in dispatch
453. response = handler(request, *args, **kwargs)
File "/var/www/display/env/lib/python2.7/site-packages/rest_framework/decorators.py" in handler
50. return func(*args, **kwargs)
File "/var/www/display/portal/views.py" in screenshot
57. serializer=portalimage(details, data=request.DATA, files=request.FILES)
File "/var/www/display/env/lib/python2.7/site-packages/rest_framework/serializers.py" in __init__
94. super(BaseSerializer, self).__init__(**kwargs)
Exception Type: TypeError at /screenshot/5caed0
Exception Value: __init__() got an unexpected keyword argument 'files'
答案 0 :(得分:0)
如果您正在使用DRF v3,则应该可以使用
serializer = portalimage(details, data=request.data)
正如评论中所提到的,文件并不是有效的kwarg,但是在查看DRF ViewSet代码时,没有提及文件,但是(根据经验)它"只是工作"。
此外,您需要确保将Content-Type标题设置为" multipart / form-data"