简体   繁体   English

Django REST FileUpload序列化程序返回{'file':None}

[英]Django REST FileUpload serializer returns {'file': None}

I've been working on a Django project that requires a file upload. 我一直在研究需要文件上传的Django项目。 I use API approach in my app designs using django-rest-framework. 我在使用django-rest-framework的应用程序设计中使用API​​方法。 I created my model, APIView, and serializer but unfortunately every time the request goes through the serializer the upload.data returns {'file': None}. 我创建了我的模型,APIView和序列化程序,但不幸的是,每次请求通过序列化程序时,upload.data都会返回{'file':None}。 If I just use request.FILES['file'] it returns the file no problem but I want to use the serialized data. 如果我只使用request.FILES ['file']它返回文件没问题,但我想使用序列化数据。 I'm using dropzone js on the front end to upload the file. 我正在前端使用dropzone js上传文件。 Here is my code below. 这是我的代码如下。

HTML HTML

{% extends 'base_profile.html' %}
{% load static %}
{% block title %}File Import{% endblock %}
{% block pagetitle %}File Import{% endblock %}
{% block content %}
<div class="widget">
    <div class="widget-heading clearfix">
      <h3 class="widget-title pull-left list-inline">CSV </h3>
      <button type="button" class="btn btn-primary pull-right"><i class="ti-upload mr-5"></i> Upload</button>
    </div>
    <div class="widget-body">
      <form id="type-dz" class="dropzone">{% csrf_token %}</form>
    </div>
</div>

{% endblock %}
{% block js %}
<script type="text/javascript">
    $("#type-dz").dropzone({
        url: "{% url 'api_import:file' %}",
        paramName: "file",
        acceptedFiles: ".csv",
        maxFilesize: 2,
        maxThumbnailFilesize: .5,
        dictDefaultMessage: "<i class='icon-dz fa fa-file-text-o'></i>Drop files here to upload"
});
</script>
{% endblock %}

urls.py urls.py

urlpatterns = [
    url(r'^api/import/', include('api.import_api.urls', namespace="api_import")),
]

api/urls.py API / urls.py

urlpatterns = [
    url(r'^file/', FileImport.as_view(), name='file'),
]

views.py views.py

class FileImport(APIView):
    parser_classes = (MultiPartParser, FormParser,)
    serializer = ImportSerializer

    def post(self, request, format=None):
        upload = self.serializer(data=request.FILES)

        if upload.is_valid():
            file = FileUpload(file=upload.data['file'], uploaded_by=request.user.profile)
            file.save()
            return Response({'success': 'Imported successfully'})
        else:
            return Response(upload.errors, status=400)

serializers.py serializers.py

class ImportSerializer(serializers.Serializer):
    file = serializers.FileField()

models.py models.py

class FileUpload(models.Model):
    file = models.FileField(upload_to='files/%Y/%m/%d')
    date_uploaded = models.DateTimeField(auto_now=True)
    uploaded_by = models.ForeignKey('UserProfile', blank=True, null=True)

It would be helpful to see how you are uploading the file. 看看如何上传文件会很有帮助。 If you are using a multipart/form-data request and providing the json for "file" properly, the most likely thing is that the file is failing validation for some reason. 如果您正在使用multipart / form-data请求并正确地为“file”提供json,那么最有可能的原因是该文件由于某种原因未通过验证。

If you can, it might also be helpful to test from the browsable api (as that guarantees nothing is wrong with your request). 如果可以的话,从可浏览的api进行测试也可能会有所帮助(因为这可以保证您的请求没有任何问题)。

Edit: 编辑:
The issue was that the validated_data field should be used instead of the data field after calling is_valid() . 问题是在调用is_valid()之后应该使用validated_data字段而不是data字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM