我创建了一个带有 ImageField 的简单模型,我想使用 django-rest-framework + django-rest-swagger 创建一个 api 视图,该视图已记录并能够上传文件.
I created a simple Model with an ImageField and I wanna make an api view with django-rest-framework + django-rest-swagger, that is documented and is able to upload the file.
这是我得到的:
models.py
from django.utils import timezone
from django.db import models
class MyModel(models.Model):
source = models.ImageField(upload_to=u'/photos')
is_active = models.BooleanField(default=False)
created_at = models.DateTimeField(default=timezone.now)
def __unicode__(self):
return u"photo {0}".format(self.source.url)
serializer.py
from .models import MyModel
class MyModelSerializer(serializers.ModelSerializer):
class Meta:
model = MyModel
fields = [
'id',
'source',
'created_at',
]
views.py
from rest_framework import generics
from .serializer import MyModelSerializer
class MyModelView(generics.CreateAPIView):
serializer_class = MyModelSerializer
parser_classes = (FileUploadParser, )
def post(self, *args, **kwargs):
"""
Create a MyModel
---
parameters:
- name: source
description: file
required: True
type: file
responseMessages:
- code: 201
message: Created
"""
return super(MyModelView, self).post(self, *args, **kwargs)
urls.py
from weddings.api.views import MyModelView
urlpatterns = patterns(
'',
url(r'^/api/mymodel/$', MyModelView.as_view()),
)
对我来说,这应该很简单.但是,我无法使上传工作.我总是得到这个错误响应:
For me this should be pretty simple. However, I can't make the upload work. I always get this error response:
我已经从 django-rest 阅读了这部分文档-框架:
如果与 FileUploadParser 一起使用的视图使用文件名 URL 关键字参数调用,则该参数将用作文件名.如果在没有文件名 URL 关键字参数的情况下调用它,则客户端必须在 Content-Disposition HTTP 标头中设置文件名.例如 Content-Disposition:附件;文件名=upload.jpg.
但是,标题是由 django-rest-swagger 在 Request Payload 属性中传递的(来自 chrome 控制台).
However the Header is being passed by django-rest-swagger in the Request Payload property (from chrome console).
如果需要更多信息,请告诉我.
If any more info is necessary, please let me know.
我正在使用 Django==1.8.8
、djangorestframework==3.3.2
和 django-rest-swagger==0.3.4代码>.
I'm using Django==1.8.8
, djangorestframework==3.3.2
and django-rest-swagger==0.3.4
.
这是我想出的最终解决方案:
This is the final solution I came up with:
from rest_framework import generics
from rest_framework.parsers import FormParser, MultiPartParser
from .serializer import MyModelSerializer
class MyModelView(generics.CreateAPIView):
serializer_class = MyModelSerializer
parser_classes = (FormParser, MultiPartParser)
def post(self, *args, **kwargs):
"""
Create a MyModel
---
parameters:
- name: source
description: file
required: True
type: file
responseMessages:
- code: 201
message: Created
"""
return super(MyModelView, self).post(self, *args, **kwargs)
我所要做的就是将解析器从 FileUploadParser
更改为 (FormParser, MultiPartParser)
All I had to do was change the parsers from FileUploadParser
to (FormParser, MultiPartParser)
这篇关于Django REST 框架 + Django REST Swagger + ImageField的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!