Know How to Deploy Python Django Application?

Posted on

Django is a powerful web framework that simplifies the deployment of Python websites and applications. It streamlines the web development process, allowing you to focus on writing code efficiently.

This guide will walk you through the process of deploying a Python Django web application.

Let’s get started!

Creating a New Project

To create a new project, we’ll use the startproject command. This will create a new project named djangoproject. Make sure to include the period (.) at the end of the command to install it in the current directory.

(.venv) > django-admin startproject django_project .

The .venv directory may be hidden initially, but it is present.

├── django_project
│   ├── __init__.py
│   ├── asgi.py
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
├── manage.py
└── .venv/

The virtual environment (.venv) was created first, and then Django added a django_project directory and a manage.py file. The django_project directory contains five files:

__init__.py: This indicates that the files in this folder are part of a Python package, enabling imports from other directories.

asgi.py: Asynchronous Server Gateway Interface (ASGI) is a specification for building asynchronous web services using Python.

settings.py: This file controls the overall settings of your Django project.

urls.py: This file defines how Django routes URL requests to specific web pages.

wsgi.py: Web Server Gateway Interface (WSGI) enables Django to serve web pages.

The manage.py file is not part of the django_project but is used to execute commands like running the local server or creating new applications.

Let’s create a test server using Django’s built-in development server. The runserver command is located within manage.py.

# Windows
(.venv) > python manage.py runserver

# macOS
(.venv) % python3 manage.py runserver

You should now see a message confirming the successful installation of your Python Django application.

Note that the output includes a warning about 18 unapplied migrations.

To remove these warnings, stop the server with Control+c and then run the command python manage.py migrate.

# Windows
> python manage.py migrate

# macOS
% python3 manage.py migrate

Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying admin.0003_logentry_add_action_flag_choices... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying auth.0010_alter_group_name_max_length... OK
  Applying auth.0011_update_proxy_permissions... OK
  Applying auth.0012_alter_user_first_name_max_length... OK
  Applying sessions.0001_initial... OK

Django has created a SQLite database and migrated its built-in apps. A new file, db.sqlite3 is now present.

├── django_project
│   ├── __init__.py
│   ├── asgi.py
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
├── db.sqlite3  # new
├── manage.py
└── .venv/

Now, if you run python manage.py runserver again, you shouldn’t see any migration warnings.

Creating an Application

Django organizes code using the concepts of projects and applications. A single top-level Django project can contain multiple applications. For instance, an e-commerce website might have separate apps for user authentication, payments, etc.

These applications all live within a single project.

# Windows
(.venv) > python manage.py startapp pages

# macOS
(.venv) % python3 manage.py startapp pages

Django created a new pages directory, containing the following files:

├── pages
│   ├── __init__.py
│   ├── admin.py
│   ├── apps.py
│   ├── migrations
│   │   └── __init__.py
│   ├── models.py
│   ├── tests.py
│   └── views.py

Here’s what each of these files does:

admin.py: Configuration file for the built-in Django Admin application.

apps.py: Configuration file for the application.

migrations: Tracks changes to your model.py file and keeps the database in sync.

tests.py: Used for writing and running specific tests for the application.

views.py: Handles the request/response logic for your web application.

Even though the pages app has been created, Django does not know about it. You need to add it to the django_project/settings.py file.

In your text editor, open the settings.py file and find the INSTALLD_APPS list. You’ll see a number of built-in Django applications. Add the pages.apps.PagesConfig entry to the bottom of this list.

# django_project/settings.py
INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "pages.apps.PagesConfig",  # new
]

If you have Black installed, it might change single quotes (‘) to double quotes (“) on save.

PagesConfig is the name of the configuration class inside the pages/apps.py file:

# pages/apps.py
from django.apps import AppConfig

class PagesConfig(AppConfig):
    default_auto_field = "django.db.models.BigAutoField"
    name = "pages"

Hello World

In Django, the Model-View-Template (MVT) pattern requires four main components to power a dynamic webpage:

models.py

views.py

template.html

urls.py

Let’s start by creating the first view. Update the views.py file within the pages application as follows:

# pages/views.py
from django.http import HttpResponse

def homePageView(request):
    return HttpResponse("Hello, World!")

This function, homePageView, takes a request and returns a response with the text “Hello, World!”.

Configuring URLs

Next, you need to configure the URLs. Create a new file named urls.py inside the pages app and add the following code to it:

# pages/urls.py
from django.urls import path
from .views import homePageView

urlpatterns = [
    path("", homePageView, name="home"),
]

Finally, update the django_project/urls.py file. It’s typical for a Django project to contain several applications. Configure your URLs so they route requests to relevant applications.

# django_project/urls.py
from django.contrib import admin
from django.urls import path, include  # new

urlpatterns = [
    path("admin/", admin.site.urls),
    path("", include("pages.urls")),  # new
]

First, we import include and then create a new URL for the pages app. When a user visits the homepage, they’ll be routed to the pages app, and then to the homePageView, as defined in pages/urls.py.

To ensure everything is working correctly, restart the Django development server:

# Windows
(.venv) > python manage.py runserver

# macOS
(.venv) % python3 manage.py runserver

Now, if you refresh your browser, you should see “Hello, World!”.

This concludes the process of creating a basic Python Django application.

Leave a Reply

Your email address will not be published. Required fields are marked *