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.8
(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.

12 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. 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”

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.