我想这样做,以便我可以将文件和文本上传到我的服务器端点。
这是curl的一个示例帖子,我想要工作:
curl -X POST https://mydomain.com/myapp/ -u user:pass -F "body=test" -F "eyecon.png=@/Users/myaccount/myproject/eyecon.png"
问题是,当我运行它时,我收到此错误消息:
{"non_field_errors": ["No input provided"]}
我浏览了Django Rest Framework代码,它只从一个位置生成此错误消息,用于处理request.DATA
和request.FILES
都为空/缺失时的情况。所以我怀疑我的问题是在配置文件中的某个地方(可能是Apache,Django或Django Rest Kit的配置,我搞砸了)。我希望有人会告诉我,我在某处错过了一条线路,这将是一个快速而简单的解决方案。
但是,只是因为它不是配置问题而且实际上我的代码存在问题,这里的所有代码都与此相关:
views.py
class MessageList(generics.ListCreateAPIView):
permission_classes = (IsAuthenticatedOrReadOnly,)
queryset = Message.objects.all()
serializer_class = MessageSerializer
def pre_save(self, obj):
obj.owner = self.request.user
serializers.py
class MessageSerializer(serializers.ModelSerializer):
owner = serializers.Field(source='owner.username')
def __init__(self, instance=None, data=None, files=None,
context=None, partial=False, many=None,
allow_add_remove=False, **kwargs):
super(MessageSerializer, self).__init__(**kwargs)
for attachment in files.getlist('file', []):
Attachment(target=id, file=attachment).save()
class Meta:
model = Message
fields = ('id', 'owner', 'title', 'created', 'body')
models.py
class Message(models.Model):
created = models.DateTimeField(auto_now_add=True)
title = models.CharField(max_length=100, blank=True, default='')
body = models.TextField()
owner = models.ForeignKey('auth.User', related_name='messages')
class Meta:
ordering = ('created',)
class Attachment(models.Model):
target = models.ForeignKey('server_app.Message', related_name='attachments')
theFile = models.FileField(upload_to='attachments/')
答案 0 :(得分:1)
我的问题出在serializers.py中。当我打电话给super(...).__init__(**kwargs)
时,我忽略了传递所有其他收到的论据。因此,序列化程序抱怨没有输入,因为我没有给它输入。
通过将之前的super(...).__init__(...)
替换为:
super(MessageSerializer, self).__init__(self, instance=instance, data=data, files=files,
context=context, partial=partial, many=many,
allow_add_remove=allow_add_remove, **kwargs)