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
(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:

INSTALLED_APPS = [
- - - - - - - -
- - - - - - - -
- - - - - - - -
'rest_framework',
'file_app',
]

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():
      file_serializer.save()
      return Response(file_serializer.data, status=status.HTTP_201_CREATED)
    else:
      return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST)

We have linked the URL of ‘file_app’ to the main project folder but we haven’t created a file yet. Now, let’s create the 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:

postman

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:

postman-filled

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

postman-success

 

That’s it.

Leave a Reply

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