Deploying a Django project on AWS Lambda using Serverless (Part 1)

Deploying a Django project on AWS Lambda using Serverless (Part 1)


As a follow-up to a post where we looked at the most common questions about Django in the Cloud, now, I'd like to help you deploy your Django App on Amazon Web Services and make you more independent from other developers like DevOps and CloudOps Engineers. There are many options for doing that but I'd like to show one of them and I hope that in the end you will be able to deploy your Django App on AWS Lambda using Serverless.

I was motivated by Daniil Bratchenko's article Don’t Let Software Vendors Dictate Your Business Processes to start writing this blog post.

It is so hard to find Software that will fit all your business processes as all companies are unique. This is why many companies have decided to set up dedicated teams building Software for their specific business processes and needs. From my personal point of view, Django App on AWS Lambda using Serverless is a good solution for cases like that.

Also, you can use this approach for prototyping your projects running them at their early stage.

There are a few advantages and disadvantages of using this approach.

Advantages of using AWS Lambdas:

  • cost (AWS Lambda is cheaper comparing to AWS EC2);
  • simplicity in running and maintaining;
  • scalability;
  • quick deployment.

the disadvantages:

  • AWS Lambda requires some extra time to run your App;
  • size limit for deployment package;
  • API Gateway limitation (30-sec timeout, 6 Mb response body size);
  • it might cost more than AWS EC2 if there are too many requests.

Prepare AWS infrastructure

Probably, you are aware of a variety of AWS services required for web applications. In order to deploy a Django project on AWS Lambdas you should prepare your AWS infrastructure. There is a list of AWS services I use for my Django project:

  1. Lambdas to run our wsgi application
  2. API Gateway to handle HTTP request and send them to Lambdas
  3. S3 buckets for Lambda deployments and storing static files
  4. CloudFront distribution for serving static files from S3 bucket
  5. RDS for a database (I use Postgres)
  6. VPC with subnets
  7. EC2 for Security Groups
  8. IAM for roles and policies
  9. CloudWatch for logs

AWS Lambdas, API Gateway will be created automatically by Serverless. I will try to walk you though the process of creating all the necessary AWS resources in my following blog posts.

Create a Django project

Django startproject command allows us to create a simple Django project, in addition to that, there are some great Cookiecutter projects that can help you start your project easily (For example Cookiecutter Django). I use default django-admin startproject cli command in this example.

pip install django
django-admin startproject django_aws_lambda

Configure requirements

There are many options to store your project requirements, for example requirements.txt, Pipfile, pyproject.toml. You can one of these options. I'm using requirements.txt here.

  • create requirements.txt file in a root directory of the project
  • add the following libraries to requirements.txt file:
  • create and activate virtual environments

Choose your preferred tool for managing virtual environments (like conda, pyenv, virtualenv, etc.)

  • install requirements
pip install -r requirements.txt

Create hello Django app

  • create app using startapp Django command
python startapp hello
  • create templates folder
mkdir templates
  • create index.html file in templates folder with the following lines:
{% load static %}

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
  <h1>Hello {{ name }}</h1>
<img src="{% static 'django.jpeg' %}" alt="Django" style="width: 20%">
  • create folder static in the root directory of the project

    mkdir static
  • add an image file to static folder, for example django.jpeg

  • update hello/

from django.shortcuts import render

# Create your views here.
def hello(request, resource=None):

    return render(request, "index.html", {"name": resource or 'World'})

Configure environments variables:

  • create .env file in the root directory of the project
  • configure the following variables:
DB_HOST=<your database host>
DB_USER=<your database user name>
DB_PASSWORD=<your database password>
DB_NAME=<your database name>
DJANGO_SECRET_KEY=<some django secret key>
AWS_S3_CDN_DOMAIN=<your Cloud Front distribution, like: `<distribution id>`>
AWS_S3_REGION_NAME=<your AWS region>
AWS_STORAGE_BUCKET_NAME=<AWS s3 bucket for static files with punlic policies>
DEPLOYMENT_BUCKET=<AWS s3 bucket for deployment>
AWS_KEY_ID=<your AWS Key Id>
AWS_SECRET=<your AWS Secret>
DJANGO_ADMIN_URL=<Django admin url>
DJANGO_ALLOWED_HOSTS=<list of allowed hosts separated by coma>

Create configuration for local development and production

  • update in django_aws_lambda folder with the following lines:
Django settings for django_aws_lambda project.

Generated by 'django-admin startproject' using Django 1.11.29.

For more information on this file, see

For the full list of settings and their values, see

from pathlib import Path

import environ

ROOT_DIR = Path(__file__).resolve(strict=True).parent.parent
env = environ.Env()
READ_DOT_ENV_FILE = env.bool('DJANGO_READ_DOT_ENV_FILE', default=True)
    env.read_env(str(ROOT_DIR / '.env'))

# Quick-start development settings - unsuitable for production
# See

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = env('DJANGO_SECRET_KEY', default='<some-secured-key>')
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False

ALLOWED_HOSTS = env.list('DJANGO_ALLOWED_HOSTS', default=['', 'localhost'])


ROOT_URLCONF = 'django_aws_lambda.urls'

        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            str(ROOT_DIR / 'templates'),
            str(ROOT_DIR / 'staticfiles'),
        'OPTIONS': {
            'loaders': [
            'context_processors': [

WSGI_APPLICATION = 'django_aws_lambda.wsgi.application'

# Database

    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': ROOT_DIR / "db.sqlite3",

# Password validation
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',

# Internationalization



USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)

STATIC_ROOT = str(ROOT_DIR / 'staticfiles')
STATIC_URL = '/static/'

STATICFILES_DIRS = [str(ROOT_DIR / 'static')]
MEDIA_ROOT = str(ROOT_DIR / 'media')
MEDIA_URL = '/media/'
  • create and files inside django_aws_lambda folder on the same level as
  • add the following lines to
from .settings import *  # noqa

DEBUG = True
  • add the following lines to
from .settings import *  # noqa

DEBUG = False
DATABASES["default"] = {
    'ENGINE': 'django.db.backends.postgresql',
    'NAME': env("DB_NAME"),
    'USER': env("DB_USER"),
    'HOST': env("DB_HOST"),
    'PORT': '5432',
DATABASES["default"]["ATOMIC_REQUESTS"] = True  # noqa F405
DATABASES["default"]["CONN_MAX_AGE"] ="CONN_MAX_AGE", default=60)  # noqa F405
INSTALLED_APPS += ["storages"]  # noqa F405
_AWS_EXPIRY = 60 * 60 * 24 * 7
AWS_S3_OBJECT_PARAMETERS = {"CacheControl": f"max-age={_AWS_EXPIRY}, s-maxage={_AWS_EXPIRY}, must-revalidate"}
AWS_S3_REGION_NAME = env("AWS_S3_REGION_NAME", default=None)
STATICFILES_STORAGE = "django_aws_lambda.utils.StaticRootS3Boto3Storage"
COLLECTFAST_STRATEGY = "collectfast.strategies.boto3.Boto3Strategy"
STATIC_URL = f"https://{aws_s3_domain}/static/"
DEFAULT_FILE_STORAGE = "django_aws_lambda.utils.MediaRootS3Boto3Storage"
MEDIA_URL = f"https://{aws_s3_domain}/media/"

TEMPLATES[-1]["OPTIONS"]["loaders"] = [  # type: ignore[index] # noqa F405
  • update file in django_aws_lambda folder with the following lines:
WSGI config for django_aws_lambda project.

It exposes the WSGI callable as a module-level variable named ``application``.

For more information on this file, see

WSGI config for django_aws_lambda project.

It exposes the WSGI callable as a module-level variable named ``application``.

For more information on this file, see

import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_aws_lambda.production')

application = get_wsgi_application()
  • update file in django_aws_lambda folder with the following lines:
"""django_aws_lambda URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
from django.contrib import admin
from django.urls import path

from hello.views import hello

urlpatterns = [
    path('', hello),
    path('<path:resource>', hello),
  • update with the following lines:
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys

def main():
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'django_aws_lambda.production')
        from import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc

if __name__ == '__main__':
  • create a folder utils inside django_aws_lambda
  • create file inside utils folder with the following lines:
from storages.backends.s3boto3 import S3Boto3Storage

class StaticRootS3Boto3Storage(S3Boto3Storage):
    location = "static"
    default_acl = "public-read"

class MediaRootS3Boto3Storage(S3Boto3Storage):
    location = "media"
    file_overwrite = False

Run Django project locally

  • set environment variable with a path to Django local configuration file
export DJANGO_SETTINGS_MODULE=django_aws_lambda.local
  • migrate database changes
python migrate
  • create a superuser in the database
python createsuperuser

Then provide a username, user email, password, and confirm the password

  • collect static files
python collectstatic
  • run server locally
python runserver

Create serverless configuration

  • initialize npm:
npm init
  • install serverless
npm install -g serverless
  • install serverless plugins
npm install -P serverless-dotenv-plugin
npm install -P serverless-prune-plugin
npm install -P serverless-python-requirements
npm install -P serverless-wsgi
  • create serverless.yaml file with the following configuration:
service: django-aws-lambda

  - serverless-dotenv-plugin
  - serverless-prune-plugin
  - serverless-python-requirements
  - serverless-wsgi
useDotenv: true

    logging: false
    dockerizePip: non-linux
    zip: true
    fileName: requirements.txt
  stage: ${env:STAGE}
    app: django_aws_lambda.wsgi.application
    packRequirements: false
    automatic: true
    number: 3

  - app:
      handler: wsgi_handler.handler
        - http: ANY /
        - http: ANY /{proxy+}
      timeout: 30

  name: aws
  role: arn:aws:iam::<role_id>:role/<role_name>
  profile: <your-profile-name>  # make sure that you configured aws profile using `aws configure --profile <your-profile-name>`
  region: us-east-1
  runtime: python3.8
  versionFunctions: false
  stage: ${env:STAGE}
  timeout: 60
      - <your-security-group-id>
      - <your-security-group-id>
      - <your-subnet-id>
      - <your-subnet-id>
    name: ${env:DEPLOYMENT_BUCKET}
    shouldStartNameWithService: true
  lambdaHashingVersion: 20201221

    - .env
    - .git/**
    - .github/**
    - .serverless/**
    - static/**
    - .cache/**
    - .pytest_cache/**
    - node_modules/**

Use Docker for deploying your Django project to AWS Lambda using Serverless

  • run Amazon Linux 2 docker image:
docker run -it -v $(pwd):/root/src/ -v /Users/<your_user>/.aws:/root/.aws amazonlinux:latest bash
  • install the necessary Unix dependencies:
yum install sudo -y
sudo yum install -y gcc openssl-devel bzip2-devel libffi-devel wget tar sqlite-devel gcc-c++ make
  • install node.js version 14:
curl -sL | sudo -E bash - 
sudo yum install -y nodejs
  • install Python 3.8.7:
cd /opt
sudo wget
sudo tar xzf Python-3.8.7.tgz
cd Python-3.8.7
sudo ./configure --enable-optimizations
sudo make altinstall
sudo rm -f /opt/Python-3.8.7.tgz
  • create python and pip aliases:
alias python='python3.8'
alias pip='pip3.8'
  • update pip and setuptools:
pip install --upgrade pip setuptools
  • install serverless:
npm install -g serverless
  • move to project directory
cd /root/src/
  • install requirements inside docker container:
pip install -r requirements.txt
  • set environment variable with a path to django production configuration file
export DJANGO_SETTINGS_MODULE=django_aws_lambda.production
  • migrate database changes
python migrate
  • create a superuser in the database
python createsuperuser

Then provide a username, user email, password, and confirm the password

  • collect static files to AWS S3 bucket
python collectstatic

If you get NoCredentialsError from botocore you should add to environment variables AWS_PROFILE:

export AWS_PROFILE=<your-aws-profile-name>
  • install serverless packages from package.json
npm install
  • deploy your Django project to AWS Lambda using Serverless
serverless deploy -s production

Your response will look like that:

Serverless: Adding Python requirements helper to ....
Serverless: Generated requirements from /root/src/requirements.txt in /root/src/.serverless/requirements.txt...
Serverless: Installing requirements from /root/.cache/serverless-python-requirements/ ...
Serverless: Using download cache directory /root/.cache/serverless-python-requirements/downloadCacheslspyc
Serverless: Running ...
Serverless: Zipping required Python packages for ....
Serverless: Using Python specified in "runtime": python3.8
Serverless: Packaging Python WSGI handler...
Serverless: Packaging service...
Serverless: Excluding development dependencies...
Serverless: Removing Python requirements helper from ....
Serverless: Injecting required Python packages to package...
Serverless: Uploading CloudFormation file to S3...
Serverless: Uploading artifacts...
Serverless: Uploading service file to S3 (60.48 MB)...
Serverless: Validating template...
Serverless: Updating Stack...
Serverless: Checking Stack update progress...
Serverless: Stack update finished...
Service Information
service: <your-serverless-service-name>
stage: production
region: <your-aws-region>
stack: <your-serverless-service-name>-pronduction
resources: 8
api keys:
  ANY - https://<some-id>.execute-api.<your-aws-region>
  ANY - https://<some-id>.execute-api.<your-aws-region>{proxy+}
  app: <your-serverless-service-name>-production-app
Serverless: Prune: Running post-deployment pruning
Serverless: Prune: Querying for deployed function versions
Serverless: Prune: <your-serverless-service-name>-production-app has 3 additional versions published and 0 aliases, 0 versions selected for deletion
Serverless: Prune: Pruning complete.
Serverless: Removing old service artifacts from S3...

Serverless: Announcing Metrics, CI/CD, Secrets and more built into Serverless Framework. Run "serverless login" to activate for free..

Now, your Django Project will be available at this URL: https://<some-id>.execute-api.<your-aws-region> image


Here is a link to a GitHub repository with the code shown in this blog post.

If you want to learn more about Django projects on AWS Lambdas follow me on Twitter (@vadim_khodak) I plan to write a post showing how to create all the necessary AWS resources for this Django project, how to add React.js client to the Django project and more.