Django Rest Framework文件上传说文档未提交

时间:2018-12-22 09:14:51

标签: django django-rest-framework

当我通过请求模块上传文件时,它说没有文档提交

models.py

class Apidocument(models.Model):
    iden = models.CharField(max_length=255)
    document = models.FileField(upload_to='media/documents')
    uploaded_at = models.DateTimeField(auto_now_add=True)

serializer.py

class DataSerializer(serializers.ModelSerializer):
    document = serializers.FileField(max_length=None,use_url =True)
    class Meta():
        model = Apidocument
        fields = ('uploaded_at','document')

views.py

class ApiViewSet(viewsets.ModelViewSet):
    queryset = Apidocument.objects.all().order_by('-uploaded_at')
    serializer_class = DataSerializer


files = {"file": ('b839', open('/home/user/b839.jpeg', 'rb'), 'multipart/form-data')}
resp = requests.post('http://localhost:8000/api/upload/', files=files)

1 个答案:

答案 0 :(得分:0)

好吧,您正在使用ModelSerializer,然后在序列化程序上定义了document字段,我认为不需要在序列化程序上将文档field指定为ModelSerializer无论如何都应该包括它。

此外,由于您将字段名用作document,因此在与文件关联的请求中需要文档密钥(至少在xhr中是如此)。因此,您的请求对象应如下所示:

files = {"document": ('b839', open('/home/user/b839.jpeg', 'rb'), 'multipart/form-data')}

希望这行得通。