Menu

Log in

Sign up

From beginner to master of web design, coding, infrastructure operation, business development and marketing

  • COURSES
  • HTML & CSS Introduction
  • HTML & CSS Coding with AI
  • Linux Introduction
  • Docker Basics
  • Git & GitHub Introduction
  • JavaScript Coding with AI
  • Django Introduction
  • AWS Basics
  • Figma Introduction
  • SEO Tutorial for Beginners
  • SEO with AI
  • OTHERS
  • About
  • Terms of Service
  • Privacy Policy

© 2024 D-Libro. All Rights Reserved

Django IntroductionChapter 6. Deploy Django App

Manage Local Development and Remote Production Environment

Manage Local Development and Remote Production Environment

Managing Local and Remote Environments in Django

As the last topic of this course, we'll explain how to efficiently manage the local development environment and the remote production environment. When you launch your new web service and work with other developers, you'll need to manage both environments simultaneously. As explained earlier, there are three key points in managing the differences between the deployment and production environments.

  1. Do not share irrelevant files (.gitignore)
  2. Do not install irrelevant dependencies (requiremetns.txt)
  3. Do not set irrelevant configurations (settings.py)

This sounds easy, but it is troublesome in practice. Here, we'll summarize the key approaches using our case.

Requirements

We haven't yet explained how to differentiate the requirements files for development and production. We can use the same approach as the one used for settings files. Create the requirements directory and add three files to manage requirements: base.txt, development.txt, and production.txt. Here are the examples of the three files used in our app example.

base.txt

Rename the original requirements.txt, and keep the requirements that are commonly used for both environments.

requirements/base.txt
Django==4.1.7
django-crispy-forms
crispy-bootstrap5
django-allauth
django-environ

development.txt

In our case, we are not using any specific library for development. Just get the list from base.txt by writing -r base.txt.

requirements/development.txt
-r base.txt

production.txt

Use -r base.txt to get the list from base.txt, and add production-specific requirements — just like you did for development.txt.

  • gunicorn : application server
  • psycopg2-binary : PostgreSQL adapter (PostgreSQL itself is directly installed on Linux)
  • django-sendgrid-v5 : for SendGrid
requirements/production.txt
-r base.txt
gunicorn
psycopg2-binary
django-sendgrid-v5

In practice, we usually use more libraries. This approach will be helpful in organizing your requirements for different environments.

The pip command

When you run the pip command, you need to adjust the file path. For example, when you run the command in the local development environment, run the command like shown below.

Command Line - INPUT
pip install -r requirements/development.txt

When you run the command in the remote production environment, run the command below.

Command Line - INPUT
pip install -r requirements/production.txt

Settings

We have already explained how to structure the settings files with an example for production settings. Here, we'll summarize the final version of both files.

development.py

Bring key settings specific to the local development environment. If you have the data that you want to manage confidentially, use the .env file. You can also ignore this development.py file using the .gitignore file instead of creating the .env file for development.

settings/development.py
from .base import *
import environ

env = environ.Env()
env.read_env('.env')

SECRET_KEY = env('SECRET_KEY')

DEBUG = True

ALLOWED_HOSTS = env.list('ALLOWED_HOSTS')

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}
# Console email
#EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'

# Gmail
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = env('EMAIL_HOST_USER')
EMAIL_HOST_PASSWORD = env('EMAIL_HOST_PASSWORD')
EMAIL_PORT = 465
EMAIL_USE_TLS = False
EMAIL_USE_SSL = True
DEFAULT_FROM_EMAIL = env('DEFAULT_FROM_EMAIL')

SECRET_KEY is the same for both development and production, but we put it in each requirement file to create a consistent structure.

For EMAIL_BACKEND, keep two options – console and Gmail, but one setting should be commented out.

Here is an example of an .env file for development. ALLOWED_HOSTS can be directly written in the development.py file. This is the case when you are using your private IP address for a mobile UI design, which is explained before (Check Developing App UI on Mobile Device).

.env(for development)
SECRET_KEY=your_secret_key

ALLOWED_HOSTS=localhost,your_private_IP_address

# Gmail
EMAIL_HOST_USER = 'your_account@gmail.com'
EMAIL_HOST_PASSWORD = 'App Password'
DEFAULT_FROM_EMAIL = 'your_account@gmail.com'

production.py

Here is the final version of the productino.py example. Put confidential information in the .env file, just like you did for development.py.

settings/production.py
from .base import *
import environ

env = environ.Env()
env.read_env('.env')

SECRET_KEY = env('SECRET_KEY')

DEBUG = False

ALLOWED_HOSTS = env.list('ALLOWED_HOSTS')

DATABASES = {
    'default': {
        'ENGINE': env('DB_ENGINE'),
        'NAME': env('DB_NAME'),
        'USER': env('DB_USER'),
        'PASSWORD': env('DB_PASSWORD'),
        'HOST': env('DB_HOST'),
        'PORT': env('DB_PORT'),
    }
}

STATIC_ROOT = '/usr/share/nginx/html/static'

# SendGrid
EMAIL_BACKEND = 'sendgrid_backend.SendgridBackend'
SENDGRID_API_KEY = env('SENDGRID_API_KEY')
DEFAULT_FROM_EMAIL = env('DEFAULT_FROM_EMAIL')
SENDGRID_SANDBOX_MODE_IN_DEBUG = False
SENDGRID_TRACK_CLICKS_PLAIN = False

In the .env file, we defined the following settings:

  • SECRET_KEY
  • ALLOWED_HOSTS
  • DB settings
  • SENDGRID settings
.env(for production)
SECRET_KEY=your_secret_key

ALLOWED_HOSTS=your_public_IP_address,your_site_domain

DB_ENGINE=django.db.backends.postgresql
DB_NAME=project_d
DB_USER=project_d_user
DB_PASSWORD=project_d_pass
DB_HOST=localhost
DB_PORT=5432

DEFAULT_FROM_EMAIL=your_email
SENDGRID_API_KEY=your_API_key

Managing the .gitignore file

Managing the .gitignore file is very important in practice. If you forget to list files that should be ignored and push your code to a Git repository, reversing this action requires a lot of effort. Thus, you need to be very careful to list all the key files that should not be shared before pushing your code.

You can use gitignore.io to create your .gitignore file, but you need to make sure that you add your virtual environment directory to the list as you define the directory name. As the development and production environments are different, sharing this directory can create several problems.

Frequently used commands

As key commands for the local environment and the production environment are slightly different (e.g., file path), it is beneficial to list them up so that you can copy and paste them when you run the command.

Local development environment

Here is a list of frequently used commands for the local environment that uses our example project (you need to update the commands based on your file name or path setting).

rm -r d_env
python3 -m venv d_env
source d_env/bin/activate
python -m pip install --upgrade pip
pip install -r requirements/development.txt
python manage.py makemigrations --settings config.settings.development
python manage.py migrate --settings config.settings.development
python manage.py createsuperuser --settings config.settings.development
python manage.py runserver --settings config.settings.development

Production environment

Here is a list of frequently used commands for the production environment. The key differences with the list above are the requirement file path and the way of running the Django app. As you cannot use the runserver command in the production environment, you need to use systemctl commands.

rm -r d_env
python3 -m venv d_env
source d_env/bin/activate
python -m pip install --upgrade pip pip install -r requirements/production.txt
python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuser
python manage.py collectstatic
sudo systemctl restart project_d
systemctl status project_d

You can also learn this topic offline. Click AmazonKindle.

More Topics to Explore

Introduction to Relational Databases for Django

Relational Database

Starting a New App in Django

Start App

Introduction to Relational Databases for Django

Relational Database

Starting a New App in Django

Start App

Tags:

Dependencies

settings.py

requirements.txt

Production Environment

App Deployment

Development Environment

.env

development.py

base.py

production.py

development.txt

production.txt

Django Introduction
Course Content

Chapter 1. Django Key Concepts

Web Framework and Django

Websites vs. Django Web Apps

How Django Handles HTTP Request and HTTP Response

Django's MVT Framework

Django Templates vs. Django APIs

Chapter 2. Django Quick Start Guide

Install Python

Install Visual Studio Code

Create Project Directory

Set Up Virtual Environment

Install Django

Start Django Project

Run Server

Database Migration

URL dispatcher – urls.py

Create Superuser and Log In to Django Admin

Start App

Create HTML Templates

Create Views

Add URL Patterns

Project vs. App

Chapter 3. Django Models and Databases

Create a Database in Django

Relational Database

Create Django Models

Makemigrations and Migrate

Add Models in Django Admin – admin.py

Change Display Name of Record Objects

Django Models – Data Field Type

Django Models – Field Options

Django Models – Help Text Option

Django Models – Choices Option

Django Models – DateField with datetime Module

Django Models – Relationship Fields

Django Models – ID

Django Models – ForeignKey (OneToMany Relationship)

Django Models – OneToOneField

Django Models – ManyToManyField

Chapter 4. Create CRUD Web Application

CRUD Web Application

Basic CRUD Structure in Django

Django Generic Views

How To Write Class-Based Views with Generic Views

Generic View Basic Attributes

URL Dispatcher for CRUD Views

Django Templates for CRUD Views

Django Template Language (DTL)

Template for List Page

get_FOO_display method

Template for Detail Page

Template with Model Relations

Template for Create and Update Page

Template for Delete Page

Add Links – {% url %} tag

Extend Templates – {% extends %} tag

Check Developing App UI on Mobile Device

Django Templates with Bootstrap

Crispy Forms

Customize Views (1) – Change List Order

Customizing Views (2) – Filter Lists

Context

Customize Views (3) – Add Extra Context

Modularize Templates – {% include %} tag

Static Files in Development Environment – {% static %} tag

STATIC_URL and STATICFILES_DIRS

Create Index HTML

Chapter 5. User Management

User Authentication

Overview of User Management Functions

User Management Function Development with Django

Approaches to Building User Management Functions in Django

Django Allauth (1) – Introduction

Django Allauth (2) – Installation and Initial Settings

Django Allauth (3) – Email Verification via Console

Django Allauth (4) – Email Verification via Gmail

Django Allauth (5) – Social Login with GitHub

Django Allauth (6) – Social Login with Google

Django Allauth (7) – Allauth Template File Setup

Django Allauth (8) – Add Basic Styling with Bootstrap and Crispy Forms

Django Allauth (9) – Customize Sign-in and Sign-up Pages

User Models

Login Required – LoginRequiredMixin

User Login Status Icon on Navigation Bar

Chapter 6. Deploy Django App

Overview of Django App Deployment (1)

Overview of Django App Deployment (2)

Key Steps of Django App Deployment

Hosting Service Initial Settings (1) – AWS Lightsail setup

Hosting Service Initial Settings (2) – SSH Remote Connection

Manage Local Computer and Remote Server Simultaneously

Tips for Managing Local Development and Remote Production Environment

Hosting Service Initial Settings (3) – Clone Project Directory with GitHub

Production Database Setup

Django Production Settings (1) – Settings.py for Development and Production

Django Production Settings (2) – Production Settings

Django Production Settings (3) – django-environ and .env file

Static File Settings

Django and Dependency Installation on Production Server

Web Server and Application Server in Django

Application Server Setup – Gunicorn

Web Server Setup – Nginx

Domain Setup

SSL Setup – Certbot

Email Setting – SendGrid

Social Login for Production

Manage Local Development and Remote Production Environment

Chapter 1. Django Key Concepts

Web Framework and Django

Websites vs. Django Web Apps

How Django Handles HTTP Request and HTTP Response

Django's MVT Framework

Django Templates vs. Django APIs

Chapter 2. Django Quick Start Guide

Install Python

Install Visual Studio Code

Create Project Directory

Set Up Virtual Environment

Install Django

Start Django Project

Run Server

Database Migration

URL dispatcher – urls.py

Create Superuser and Log In to Django Admin

Start App

Create HTML Templates

Create Views

Add URL Patterns

Project vs. App

Chapter 3. Django Models and Databases

Create a Database in Django

Relational Database

Create Django Models

Makemigrations and Migrate

Add Models in Django Admin – admin.py

Change Display Name of Record Objects

Django Models – Data Field Type

Django Models – Field Options

Django Models – Help Text Option

Django Models – Choices Option

Django Models – DateField with datetime Module

Django Models – Relationship Fields

Django Models – ID

Django Models – ForeignKey (OneToMany Relationship)

Django Models – OneToOneField

Django Models – ManyToManyField

Chapter 4. Create CRUD Web Application

CRUD Web Application

Basic CRUD Structure in Django

Django Generic Views

How To Write Class-Based Views with Generic Views

Generic View Basic Attributes

URL Dispatcher for CRUD Views

Django Templates for CRUD Views

Django Template Language (DTL)

Template for List Page

get_FOO_display method

Template for Detail Page

Template with Model Relations

Template for Create and Update Page

Template for Delete Page

Add Links – {% url %} tag

Extend Templates – {% extends %} tag

Check Developing App UI on Mobile Device

Django Templates with Bootstrap

Crispy Forms

Customize Views (1) – Change List Order

Customizing Views (2) – Filter Lists

Context

Customize Views (3) – Add Extra Context

Modularize Templates – {% include %} tag

Static Files in Development Environment – {% static %} tag

STATIC_URL and STATICFILES_DIRS

Create Index HTML

Chapter 5. User Management

User Authentication

Overview of User Management Functions

User Management Function Development with Django

Approaches to Building User Management Functions in Django

Django Allauth (1) – Introduction

Django Allauth (2) – Installation and Initial Settings

Django Allauth (3) – Email Verification via Console

Django Allauth (4) – Email Verification via Gmail

Django Allauth (5) – Social Login with GitHub

Django Allauth (6) – Social Login with Google

Django Allauth (7) – Allauth Template File Setup

Django Allauth (8) – Add Basic Styling with Bootstrap and Crispy Forms

Django Allauth (9) – Customize Sign-in and Sign-up Pages

User Models

Login Required – LoginRequiredMixin

User Login Status Icon on Navigation Bar

Chapter 6. Deploy Django App

Overview of Django App Deployment (1)

Overview of Django App Deployment (2)

Key Steps of Django App Deployment

Hosting Service Initial Settings (1) – AWS Lightsail setup

Hosting Service Initial Settings (2) – SSH Remote Connection

Manage Local Computer and Remote Server Simultaneously

Tips for Managing Local Development and Remote Production Environment

Hosting Service Initial Settings (3) – Clone Project Directory with GitHub

Production Database Setup

Django Production Settings (1) – Settings.py for Development and Production

Django Production Settings (2) – Production Settings

Django Production Settings (3) – django-environ and .env file

Static File Settings

Django and Dependency Installation on Production Server

Web Server and Application Server in Django

Application Server Setup – Gunicorn

Web Server Setup – Nginx

Domain Setup

SSL Setup – Certbot

Email Setting – SendGrid

Social Login for Production

Manage Local Development and Remote Production Environment