How to Upload Files in AWS S3 using the Django Rest Framework?

Published On: 01/12/2022 | Category: Django

Hi Dev,

I will explain step by step tutorial how to upload files in aws s3 using the django rest framework. I would like to show you how to upload image to aws s3 using the django rest framework. it's simple example of django upload files to aws s3 example. we will help you to give example of django admin upload image to aws s3 example.

You must take a few steps. I will also demonstrate how to set up an S3 bucket account and use it with django. Then I'll make a simple files upload example for you to understand. Let us proceed as follows

Here i explained simply step by step example of how to upload files in aws s3 using the django rest framework.

Step 1: Create a Project

In this step, we’ll create a new django project using the django-admin. Head back to your command-line interface and run the following command:

django-admin startproject example

Step 2: Create a App

Now we'll create a single app called core to store a list of post names. We're keeping things intentionally basic. Stop the local server with Control+c and use the startapp command to create this new app.

python3 startapp core

Step 3: Update

Then update INSTALLED_APPS within our file to notify Django about the app.



STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' 

Step 4: Install require Django-storages

In this article, we will use Django-storages to connect to the AWS S3 bucket.

Django-storages is a collection of Django framework-specific storage backends. We'll use the AWS S3 integration from the Django-storages package.

pip install django-storages
pip install boto3

Step 5: Create S3 Bucket

First you need to create bucket and user so let's follow bellow step:

1. Go to Amazon Web Service Console and Login.

2. Click on S3 from Service Lists

3. Click on "Create Bucket" button and you will found bellow forms. you can enter your bucket name there.

4. Create Create IAM User. Click here to create IAM User.

5. Click on "Create User" button as bellow show you.

6. Next Add User Name and select "Programmatic access" from access type. then click on next.

7. Next Select “Attach Existing Policy Directly” and choose "AmazonS3FullAccess" from permission link.

8. It's optional so you can skip and click to next.

9. You can view user details and then click on "Create User" button.

10. Now you will see created user in link. there is a "Access Key ID" and "Secret Access Key" that we need on .env files.

Step 6: Create a Model

In this step we will require the database model for storing contacts.Open the core/ file and add the following code:

from django.db import models
class Article(models.Model):
    title = models.CharField(max_length=30)
    document = models.FileField(max_length=30)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    class Meta:
        verbose_name_plural = 'Articles'

Ok, all set. We can engender a migrations file for this change, then integrate it to our database via migrate.

python makemigrations
python migrate

Step 7: Creating the Serializers

In this step, we need to create Serializers allow complex data such as querysets and model instances to be converted to native Python datatypes that can then be easily rendered into JSON, XML or other content types. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data. Let’s start creating a serializer.

from rest_framework import serializers
from .models import Article
class ArticleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Article
        fields = '__all__'

Step 8: Creating the Views

In this step, we need to configure views open the core/ file and add:

from rest_framework import viewsets, parsers
from .models import Article
from .serializers import ArticleSerializer

class ArticleViewset(viewsets.ModelViewSet):
    queryset = Article.objects.all()
    serializer_class = ArticleSerializer
    parser_classes = [parsers.MultiPartParser, parsers.FormParser]
    http_method_names = ['get', 'post', 'patch', 'delete']

Step 9: Creating URLs

In this section, we need a file within the core app however Django doesn't create one for us with the startapp command. Create core/ with your text editor and paste below code.

from rest_framework.routers import SimpleRouter
from .views import ArticleViewset
router = SimpleRouter()
router.register('accounts', ArticleViewset)
urlpatterns = router.urls

Next, we require to add a URL path for our example app which can be done by importing include and setting a path for it.

from django.conf import settings  # new
from django.conf.urls.static import static  # new
from django.contrib import admin
from django.urls import path
urlpatterns = [
    path('api/', include('rest_framework.urls')),
    path('', include('core.urls')),
if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

Run the Server

In this step, we’ll run the local development server for playing with our app without deploying it to the web.

python runserver
DRF View:

AWS Upload Image:

I hope it will help you....

Happy Coding!