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 manage.py startapp core

Step 3: Update setting.py

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

settings.py
....
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',

    'core',
]

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

AWS_ACCESS_KEY_ID = <YOUR AWS ACCESS KEY>
AWS_SECRET_ACCESS_KEY = <YOUR AWS SECRET KEY>
AWS_STORAGE_BUCKET_NAME = <YOUR AWS S3 BUCKET NAME>
AWS_S3_SIGNATURE_VERSION = 's3v4'
AWS_S3_REGION_NAME = <YOUR AWS S3 BUCKET LOCATION>
AWS_S3_FILE_OVERWRITE = False
AWS_DEFAULT_ACL = None
AWS_S3_VERIFY = True
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/models.py file and add the following code:

core/models.py
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 manage.py makemigrations
python manage.py 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.

core/serializers.py
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/views.py file and add:

core/views.py
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 urls.py file within the core app however Django doesn't create one for us with the startapp command. Create core/urls.py with your text editor and paste below code.

core/urls.py
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.

example/urls.py
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('admin/', admin.site.urls),
    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 manage.py runserver
DRF View:

AWS Upload Image:

I hope it will help you....

Happy Coding!