ssk ssk - 1 year ago 99
Python Question

Django REST FileUpload serializer returns {'file': None}

I’ve been working on a Django project that requires a file upload. I use API approach in my app designs using django-rest-framework. I created my model, APIView, and serializer but unfortunately every time the request goes through the serializer the returns {'file': None}. If I just use request.FILES['file'] it returns the file no problem but I want to use the serialized data. I'm using dropzone js on the front end to upload the file. Here is my code below.


{% 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 class="widget-body">
<form id="type-dz" class="dropzone">{% csrf_token %}</form>

{% endblock %}
{% block js %}
<script type="text/javascript">
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"
{% endblock %}

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


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

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'], uploaded_by=request.user.profile)
return Response({'success': 'Imported successfully'})
return Response(upload.errors, status=400)

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

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)

Answer Source

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.

If you can, it might also be helpful to test from the browsable api (as that guarantees nothing is wrong with your request).

The issue was that the validated_data field should be used instead of the data field after calling is_valid().

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download