Uploading file using api in django rest framework

Uploading files to the server is one of the common tasks nowadays. In this tutorial, we will see how can we upload the file using the Django-rest framework.

First, let’s create a virtual environment for our Django project.

$ virtual env

Activate the virtual environment.

$ source env/bin/activate

install django and django-restframework

(env) $ pip install django==1.11.20
(env) $ pip install djangorestframework

Start a new django project with the name ‘fileupload’

(env) $ django-admin startproject fileupload

Move into the new project directory and create a new app called ‘file_app’

(env) $ cd fileupload
(env) $ python manage.py startapp file_app

So, we have created our project and also an app. Let’s set up our project for the main part.

Update ‘INSTALLED_APPS’ in settings.py file:

- - - - - - - -
- - - - - - - -
- - - - - - - -

In settings.py add the path to the directory where you would want to store the uploaded files. Add the below line at the end of settings.py file:

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, "media")

Add the media url and the ‘file_app’ urls.py in the project’s urls.py file. The final urls.py will be:

from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
  url(r'^admin/', admin.site.urls),
  url(r'^file/', include('file_app.urls')),

if settings.DEBUG:
  urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Now, everything is set up. Let’s start coding.
We will start by creating models for our app.

in file_app/models.py

from django.db import models

class File(models.Model):

  file = models.FileField(blank=False, null=False)
  remark = models.CharField(max_length=20)
  timestamp = models.DateTimeField(auto_now_add=True)

Create a new file as ‘serializers.py’ in-app directory (i.e. in ‘file_app’) and add the following code there:

from rest_framework import serializers

from .models import File

class FileSerializer(serializers.ModelSerializer):

  class Meta():
    model = File
    fields = ('file', 'remark', 'timestamp')

Let’s edit the views.py and add the following code there:

from rest_framework.views import APIView
from rest_framework.parsers import MultiPartParser, FormParser
from rest_framework.response import Response
from rest_framework import status

from .serializers import FileSerializer

class FileView(APIView):

  parser_classes = (MultiPartParser, FormParser)

  def post(self, request, *args, **kwargs):

    file_serializer = FileSerializer(data=request.data)
    if file_serializer.is_valid():
      return Response(file_serializer.data, status=status.HTTP_201_CREATED)
      return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST)

Now, let’s create the file_app/urls.py file and add the following code:

from django.conf.urls import url

from .views import FileView

urlpatterns = [
  url(r'^upload/$', FileView.as_view(), name='file-upload'),

That’s it. Now you can upload the file from frontend using this api.
Let’s try this out.

Prepare the database for the test:

(env) $ python manage.py makemigrations
(env) $ python manage.py migrate

And run the server

(env) $ python manage.py runserver

Open Postman app:


enter the url in url field and set the method to POST which is at the left of the url field. Go to Body section and make sure that ‘form-data’ is checked.

In the key field write ‘file’, which should match the name of your model field name. In this case it is ‘file’. So, I am writing ‘file’. Then from drop-down select ‘File’ instead of ‘Text’. In value field browse the file and select it.

Repeat the process for remark section. Check it from image below:


Now click send, your file will be uploaded and you will get file data in response:


That’s it.

30 thoughts on “Uploading file using api in django rest framework”

  1. ImportError at /file
    No module named urls
    Request Method: GET
    Request URL:
    Django Version: 1.8
    Exception Type: ImportError
    Exception Value:
    No module named urls
    Exception Location: C:\Users\xxxx\Anaconda2\lib\site-packages\rest_framework\compat.py in , line 26
    Python Executable: C:\Users\xxxx\Anaconda2\python.exe
    Python Version: 2.7.13
    Python Path:

    i got this error ..please help me

    1. The best way to debug an error is to follow up the error log.
      i.e. in your case see at line 2 of the error log, it says “No module named urls”,
      this case please check your urls.py for any import error.
      The import should be: “from django.conf.urls import url”

      P.S.: There is very little I can do from the given error log, if possible
      please share views.py and urls.py using github gist

    2. —–I got this exception—–:
      from django.urls import ( # noqa
      ImportError: No module named urls

      — In this code —

      from django.urls import ( # noqa
      except ImportError:
      # Will be removed in Django 2.0
      from django.urls import ( # noqa …
      RegexURLPattern as URLPattern,
      RegexURLResolver as URLResolver,
      def get_original_route(urlpattern):

  2. Thanks for the tutorial, very helpful!

    To make it a little clearer, right before the last code snippet you could say “Now, let’s create the file_app/urls.py file and add the following code:”

  3. amazing…thanx for sharing this..pls let me know which desktop environment u set up..which are the configurations…coz i love it

  4. I want to use requests lib to write a script instead of postman.

    Here’s my code :


    headers = {‘Content-Type’: ‘application/json;’, ‘Authorization’: token}
    url = “”
    fin = open(‘get-pip.py’, ‘rb’)
    files = {‘file’: fin}
    r = requests.post(url, data={‘file’:fin ,’remark’: ‘test_file’}, headers=headers)

    I get a return code of 401

    [01/May/2018 03:02:33] “POST /file/upload/ HTTP/1.1” 415 69

    Can you help me fix it , tks

  5. Hi Vivek,
    Thanks for posting this nicely.
    I tried this, and its working fine with one file upload.
    while I am trying to upload multiple files at a time, its taking only second file.
    Can you please help me out for uploading multiple files.

  6. Hi Vivek,
    How to handle image filenames with spaces, eg. (fruitapplemango.jpg)is like (fruitapple mango.jpg)

  7. Hi Vivek,
    Thanks for the post.
    How to save filename with space, If the filename “fruitapplemango.jpg” I have is having a space in middle like “fruitapple mango.jpg”

  8. Hi sir, I implemented your tutorials on uploading files in my api applications. I made some minor changes and successfully got response where the file is being uploaded. It says like this, “”.

    But when I checked the media directly, there is no file where actually uploaded there.

    Can you please help me with this?

    Thanks in advance.

  9. In serializer:

    instead of,

    class Meta():
    model = File
    fields = (‘file’, ‘remark’, ‘timestamp’)

    class Meta:
    model = File
    fields = ‘__all__’

    1. Hi Pallav,

      Yeah, we can use ‘__all__’ to include all the fields in model serializer, but it’s good practice/habit to explicitly write them. When you work on bigger models, you want the control of the data going in and out. Then again it also comes to personal preference. Thanks for your comment.

  10. TypeError at /fileupload/
    __init__() takes 1 positional argument but 2 were given
    im getting this error.what should i do?

  11. first of all, thank you for this tutorial, it works fine on postman when using form-data. But when I’m trying to write json as “application/json” I got this error:
    “The submitted data was not a file. Check the encoding type on the form.”
    how to upload image using raw -> application/json not form-data?

    many thanks,

  12. Tks for the tutorial.
    Unfortunately I’m having this error:

    Using the URLconf defined in fileupload.urls, Django tried these URL patterns, in this order:

    The empty path didn’t match any of these.

    Any hint ?

  13. Hi vivek i have used your code and its working fine. Its very easy to understand can u plz post a code for multiple file upload

  14. I have some other fields that are foreinkeys and use this file uploader with android section .
    any body know how I should get other foreinkeys to save

  15. write views.py like this:
    class FileUploadView(generics.ListCreateAPIView):
    queryset = FileUpload.objects.all()
    serializer_class = FileUploadSerializer

    automatically CREATE all fields and you also GET all fields.
    And Your views.py is very complicated.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.