我用 ImageField 创建了一个简单的模型,我想用 django-rest-framework + django-rest-swagger 创建一个 api 视图,该视图已记录并能够上传文件。
这是我得到的:
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()),
)
对我来说,这应该很简单。但是,我无法使上传工作。我总是得到这个错误响应:
我已经从django-rest-framework阅读了这部分文档:
If the view used with FileUploadParser is called with a filename URL keyword argument, then that argument will be used as the filename. If it is called without a filename URL keyword argument, then the client must set the filename in the Content-Disposition HTTP header. For example Content-Disposition: attachment; filename=upload.jpg.
但是,标头是由 django-rest-swagger 在 Request Payload 属性中传递的(来自 chrome 控制台)。
如果需要更多信息,请告诉我。
我正在使用Django==1.8.8
,djangorestframework==3.3.2
和django-rest-swagger==0.3.4
.