Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Django 5 By Example - Fifth Edition

You're reading from  Django 5 By Example - Fifth Edition

Product type Book
Published in Apr 2024
Publisher Packt
ISBN-13 9781805125457
Pages 820 pages
Edition 5th Edition
Languages
Author (1):
Antonio Melé Antonio Melé
Profile icon Antonio Melé

Table of Contents (20) Chapters

Preface 1. Building a Blog Application 2. Enhancing Your Blog and Adding Social Features 3. Extending Your Blog Application 4. Building a Social Website 5. Implementing Social Authentication 6. Sharing Content on Your Website 7. Tracking User Actions 8. Building an Online Shop 9. Managing Payments and Orders 10. Extending Your Shop 11. Adding Internationalization to Your Shop 12. Building an E-Learning Platform 13. Creating a Content Management System 14. Rendering and Caching Content 15. Building an API 16. Building a Chat Server 17. Going Live 18. Other Books You May Enjoy
19. Index

Going Live

In the previous chapter, you built a real-time chat server for students using Django Channels. Now that you have created a fully functional e-learning platform, you need to set up a production environment so that it can be accessed over the internet. Until now, you have been working in a development environment, using the Django development server to run your site. In this chapter, you will learn how to set up a production environment that is able to serve your Django project in a secure and efficient manner.

This chapter will cover the following topics:

  • Configuring Django settings for multiple environments
  • Using Docker Compose to run multiple services
  • Setting up a web server with uWSGI and Django
  • Serving PostgreSQL and Redis with Docker Compose
  • Using the Django system check framework
  • Serving NGINX with Docker
  • Serving static assets through NGINX
  • Securing connections through Transport Layer Security (TLS) / Secure...

Creating a production environment

It’s time to deploy your Django project in a production environment. You will start by configuring Django settings for multiple environments, and then you will set up a production environment.

Managing settings for multiple environments

In real-world projects, you will have to deal with multiple environments. You will usually have at least a local environment for development and a production environment for serving your application. You could have other environments as well, such as testing or staging environments.

Some project settings will be common to all environments, but others will be specific to each environment. Usually, you will use a base file that defines common settings, and a settings file per environment that overrides any necessary settings and defines additional ones.

We will manage the following environments:

  • local: The local environment to run the project on your machine
  • prod: The environment...

Using Docker Compose

You initially used Docker in Chapter 3, Extending Your Blog Application, and you have been using Docker throughout this book to run containers for different services, such as PostgreSQL, Redis, and RabbitMQ.

Each Docker container combines application source code with operating system libraries and dependencies required to run the application. By using application containers, you can improve your application portability. For the production environment, we will use Docker Compose to build and run multiple Docker containers.

Docker Compose is a tool for defining and running multi-container applications. You can create a configuration file to define the different services and use a single command to start all services from your configuration. You can find information about Docker Compose at https://docs.docker.com/compose/.

For the production environment, you will create a distributed application that runs across multiple Docker containers. Each Docker...

Serving Django through WSGI and NGINX

Django’s primary deployment platform is WSGI. WSGI stands for Web Server Gateway Interface , and it is the standard for serving Python applications on the web.

When you generate a new project using the startproject command, Django creates a wsgi.py file inside your project directory. This file contains a WSGI application callable, which is an access point to your application.

WSGI is used for both running your project with the Django development server and deploying your application with the server of your choice in a production environment. You can learn more about WSGI at https://wsgi.readthedocs.io/en/latest/.

In the following sections we will use uWSGI, an open source web server that implements the WSGI specification.

Using uWSGI

Throughout this book, you have been using the Django development server to run projects in your local environment. However, the development server is not designed for production use, and...

Securing your site with SSL/TLS

The TLS protocol is the standard for serving websites through a secure connection. The TLS predecessor is SSL. Although SSL is now deprecated, in multiple libraries and online documentation, you will find references to both the terms TLS and SSL. It’s strongly encouraged that you serve your websites over HTTPS.

In this section, you are going to check your Django project for any issues and validate it for a production deployment. You will also prepare the project to be served over HTTPS. Then, you are going to configure an SSL/TLS certificate in NGINX to serve your site securely.

Checking your project for production

Django includes a system check framework for validating your project at any time. The check framework inspects the applications installed in your Django project and detects common problems. Checks are triggered implicitly when you run management commands like runserver and migrate. However, you can trigger checks explicitly...

Configuring Daphne for Django Channels

In Chapter 16, Building a Chat Server, you used Django Channels to build a chat server using WebSockets and you used Daphne to serve asynchronous requests by replacing the standard Django runserver command. We will add Daphne to our production environment.

Let’s create a new service in the Docker Compose file to run the Daphne web server.

Edit the docker-compose.yml file and add the following lines inside the services block:

daphne:
    build: .
    working_dir: /code/educa/
    command: ["../wait-for-it.sh", "db:5432", "--",
              "daphne", "-b", "0.0.0.0", "-p", "9001",
              "educa.asgi:application"]
    restart: always
    volumes:
      - .:/code
    environment:
      - DJANGO_SETTINGS_MODULE=educa.settings.prod
      - POSTGRES_DB=postgres
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=postgres
    depends_on...

Creating a custom middleware

You already know the MIDDLEWARE setting, which contains the middleware for your project. You can think of it as a low-level plugin system, allowing you to implement hooks that get executed in the request/response process. Each middleware is responsible for some specific action that will be executed for all HTTP requests or responses.

You should avoid adding expensive processing to middleware since they are executed in every single request.

Figure 17.15 shows the middleware execution in Django:

Figure 17.15: Middleware execution in Django

When an HTTP request is received, middleware is executed in order of appearance in the MIDDLEWARE setting. When an HTTP response has been generated by Django, the response passes through all middleware back in reverse order.

Figure 17.16 shows the execution order of the middleware components included in the MIDDLEWARE setting when creating a project with the startproject management...

Implementing custom management commands

Django allows your applications to register custom management commands for the manage.py utility. For example, you used the makemessages and compilemessages management commands in Chapter 11, Adding Internationalization to Your Shop, to create and compile translation files.

A management command consists of a Python module containing a Command class that inherits from django.core.management.base.BaseCommand or one of its subclasses. You can create simple commands or make them take positional and optional arguments as input.

Django looks for management commands in the management/commands/ directory for each active application in the INSTALLED_APPS setting. Each module found is registered as a management command named after it.

You can learn more about custom management commands at https://docs.djangoproject.com/en/5.0/howto/custom-management-commands/.

You are going to create a custom management command to remind students to enroll...

Summary

In this chapter, you created a production environment using Docker Compose. You configured NGINX, uWSGI, and Daphne to serve your application in production. You secured your environment using SSL/TLS. You also implemented custom middleware and you learned how to create custom management commands.

You have reached the end of this book. Congratulations! You have learned the skills required to build successful web applications with Django. This book has guided you through the process of developing real-life projects and integrating Django with other technologies. Now, you are ready to create your own Django project, whether it is a simple prototype or a large-scale web application.

Good luck with your next Django adventure!

Expanding your project using AI

In this section, you are presented with a task to extend your project, accompanied by a sample prompt for ChatGPT to assist you. To engage with ChatGPT, visit https://chat.openai.com/. If this is your first interaction with ChatGPT, you can revisit the Expanding your project using AI section in Chapter 3, Extending Your Blog Application.

We have developed a comprehensive e-learning platform. However, when students are enrolled in multiple courses, each containing several modules, it can be challenging for them to remember where they last left off. To address this, let’s use ChatGPT in conjunction with Redis to store and retrieve each student’s progress within a course. For guidance, refer to the prompt provided at https://github.com/PacktPublishing/Django-5-by-example/blob/main/Chapter17/prompts/task.md.

When you’re refining your Python code, ChatGPT can help you explore different refactoring strategies. Discuss...

Additional resources

The following resources provide additional information related to the topics covered in this chapter:

Join us on Discord!

Read this book alongside other users, Django development experts, and the author himself. Ask questions, provide solutions to other readers, chat with the author via Ask Me Anything sessions, and much more.Scan the QR code or visit the link to join the community.

https://packt.link/Django5ByExample

lock icon The rest of the chapter is locked
You have been reading a chapter from
Django 5 By Example - Fifth Edition
Published in: Apr 2024 Publisher: Packt ISBN-13: 9781805125457
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime}