Skip to main content

Getting Started with Django

Getting Started with Django, a leading web framework written in Python

Django is a leading web framework actively supported and versioned by programming experts using a batteries-included concept. Django can help us to code from simple, one-page websites, APIs, micro-services, or complex eCommerce platforms.

It enables developers to build robust applications rapidly while helping developers to avoid security mistakes since Django takes security seriously. Django is flexible and scalable and comes with a lot of tools prebuilt into it for example, its Object relation mapper (ORM), admin dashboard, user authentication and lots more.

Getting Started with Django - Tutorial provided by AppSeed.

Django adopts the MTV (Model Template View) architectural pattern. Model determines the data structure and is a handler between the database and the view. Template keeps everything the browser renders, django uses a plain text template system. View communicates with the database using the model and sends the data to the template to be displayed.

The framework acts as a controller sending requests to the right view based on the URL configuration. Django's MVT pattern emphasizes the separation of concerns and modularity, making it easier to develop and maintain web applications with a clear separation between business logic, data access, and presentation.

✅ Why Using Django​

  • Django enables rapid development by eliminating a lot of the hassle of web development
  • Django helps developers avoid many common security mistakes
  • Django is very flexible and scalable
  • Since Django is built using Python, this gives the developer a wide range of third-party modules to select from to solve various challenges that may arise during development
  • Django has a very vibrant community and it is regularly updated

✅ Installing Django​

Before development can start with Django, it has to be installed using Python package manager (pip). Before Django is installed and development begins, there is a need to create a virtual environment, this way the development environment is isolated from the rest of our machine.

This can help prevent dependency issues and also help in reproducibility.


👉 Creating a Virtual environment​

  • From the terminal, type the following commands
$ mkdir django-tutorial
$ cd django-tutorial

mkdir creates a folder named django-tutorial that will serve as the root of the project. cd changes the directory to the folder just created.

  • Now we are prepared to create our virtual environment. Run the following code on your terminal

On Mac/Linux:

$ virtualenv venv
$ source ./venv/bin/activate
(venv)$ # ready for commands

On Windows:

$ virtualenv venv
$ venv\Scripts\activate
(venv) $ # ready for commands

virtualenv creates a virtual environment called venv, and the next line activates the virtual environment. (venv) indicates that the virtual environment is active. Now we can install Django without concerns of conflicts and dependency issues.


👉 Installing Django​

Since our virtual environment is active we can install Django and start development. In your terminal run the following commands

(venv) $ pip install django

✅ Django project​

A Django project is a collection of settings and configurations that define the structure and behavior of a web application. It is a high-level representation of a web application that includes multiple components such as models, views, templates, forms, and static files.


👉 Creating the Project​

A Django project is created using the django-admin command-line tool. django-admin startproject <project-name> is the command used to create a new Django project.

  • Run the command below to create a Django project called core
(venv) $ django-admin startproject core .

. is used to create the project in the current directory, without this Django will create a new project in a directory with the project name specified.

After running the command above, your directory structure will look like this. These files have been automatically created by Django.

├── core
│   ├── asgi.py
│   ├── __init__.py
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
└── manage.py

👉 Applying initial Database configuration​

Django comes with some database configurations which can be found in core/settings.py, the default database configuration for Django is SQLite3. Django is built to integrate with a lot of popular databases like MySQL, Postgresql, Oracle and so on. Check Django documentation here for more information on how to get started using other database engines. The command below applies the initial migration for all the installed applications for the Django project.

(venv) $ python manage.py migrate
  • Run the command below to confirm your Django project has been correctly installed
(venv) $ python manage.py runserver

This starts up a Django server, open http://127.0.0.1:8000/ in your browser, you should see the page below. You can stop the server from the terminal by using Ctrl + c. Django successful installation page


✅ Django Applications​

In Django, an application is a self-contained module of code that provides specific functionality to a project. It is a collection of models, views, templates, and other related files that work together to implement a particular feature or set of features. An application is typically stored in its directory within the project's directory structure. Each application contains a set of files that define its functionality, including:

  • Models: A model is a Python class that defines the structure of a database table and the relationships between tables. Models are used to define the data structure of the application.

  • Views: A view is a Python function that processes HTTP requests and returns HTTP responses. Views are used to define the logic for handling user requests and rendering the appropriate response.

  • Templates: A template is an HTML file that defines the layout and structure of the application's web pages. Templates are used to define the presentation layer of the application.

  • URLs: A URL is a string that maps to a view function. URLs are used to define the routing for the application.

  • Static files: Static files are files such as CSS, JavaScript, and images that are used to define the presentation layer of the application.


👉 Creating a Django APP​

Using the django-admin command from the terminal, we will be creating a Django application inside the project directory. django-admin startapp <app-name> is the command used for creating new applications.

Run the command below on your terminal to create a Django application name example

(venv) $ django-admin startapp example

With this, a new application called example has been created. The new folder structure for the project will become

├── core
│   ├── asgi.py
│   ├── __init__.py
│   ├── __pycache__
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
├── db.sqlite3
├── example
│   ├── admin.py
│   ├── apps.py
│   ├── __init__.py
│   ├── migrations
│   ├── models.py
│   ├── tests.py
│   └── views.py
└── manage.py

Although we have created an application, the Django project does not recognize our application, we will need to register the application with the project to allow the project to recognize the application.


👉 Update Settings​

To connect example to the Django project core, open the file core/settings.py and add example to the INSTALLED_APPS list.

# core/settings.py
...
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'example', # <-- NEW
]
...

Now our Django project recognizes the example application.


👉 Updating Project Routes​

Now that the Django project can recognize the example application, the next step is to give the application a route. By doing this we create a generic route that when visited, Django checks this application for resources to send back to the client.

Inside core/urls.py add the following code snippet to register the root route to the example application.

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

urlpatterns = [
path('admin/', admin.site.urls),
path('', include('example.urls')),
]

If your Django server was running when this change was made, you would be having an error. not to worry, it will be fixed in a few steps.


👉 Serving an HTML Page​

  • Edit the `core/settings file by adding a route to template files for Django to use in identifying resources to be sent as the response
# core/settings.py
...
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR / 'templates',], # change made
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
...
  • Create a folder in the root of the application templates, and create a file inside the folder name index.html. Add the code snippet below to the file.
<!-- templates/index.html -->
<!DOCTYPE html>
<html>
<head>
<title>{% block title %}{% endblock %}</title>
</head>
<body>
<div id="content">
{% block content %}
<p>This is the homepage of my example application</p>
{% endblock %}
</div>
</body>
</html>
  • Create the function below inside example/views.py, its response to a request is the template just created.
# example/views.py
...
def index(request):
return render(request, 'index.html')

render checks the templates folder for the files to be sent back to the client as a response to a request.

  • Create a file inside the example folder named urls.py and add the following code snippets.
# example/urls.py
from django.urls import path

from . import views

urlpatterns = [
path('', views.index),
]
  • Running the server again and checking the root route http://127.0.0.1:8000/ will return the page below Homepage after the creation of an application

The new folder structure will look like this

├── core
│   ├── asgi.py
│   ├── __init__.py
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
├── db.sqlite3
├── example
│   ├── admin.py
│   ├── apps.py
│   ├── __init__.py
│   ├── migrations
│   ├── models.py
│   ├── tests.py
│   ├── urls.py
│   └── views.py
├── manage.py
├── templates
│   └── index.html

✅ Update the UI​

Because Django applications are reusable, it is possible to get a predesigned application that fits into what you are developing and integrate it into your project. The Django repository is home to a lot of predesigned applications. Those applications can be installed using the Python package manager pip. For this tutorial, we will be using the django-theme-material-kit.

Install Material UI

(venv) $ pip install django-theme-material-kit

Once the theme has been installed, we need to let our Django project recognizes it as one of our applications. To do that, we will be editing INSTALLED_APPS in core/settings.py

# core/settings.py
...
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'example',
'theme_material_kit', # <-- NEW
]
...
# bottom of the file
LOGIN_REDIRECT_URL = '/'

Update Routing

Now the project recognizes the application, the next step is to add the application to the urls of our project. Inside the core/urls.py file make the following changes

# core/urls.py
...
urlpatterns = [
path('', include('theme_material_kit.urls')),
path('admin/', admin.site.urls),
path('/example', include('example.urls')),
]

Now the new application will be seen when we visit the root route / and the application created earlier will be seen when the example route is visited.

(venv) $ # Set up the database
(venv) $ python manage.py makemigrations
(venv) $ python manage.py migrate
(venv) $ python manage.py createsuperuser # Create the superuser
(venv) $ python manage.py runserver # Start the application (development mode)

Opening the URL http://127.0.0.1:8000 from your browser you will see a new application that has been installed. and opening the route http://127.0.0.1:8000/example opens the previous application that was created.

The new theme installed as application


Previous application on a new route

With predesigned themes, development can be made faster and you can focus on business-specific logic.


✅ Deploying a Django project​

The application just built will be deployed on Render and also deployed using Docker.


👉 Initial setup​

Before we can start deploying our project, we need to make some changes to our codebase.

Installing whitenoise a package used for handling the hosting of static files. From your terminal run the command below

(venv) $ pip install whitenoise[brotli]

Open core/settings.py and make the following changes

# core/settings.py
import os, random, string
...
SECRET_KEY = os.environ.get('SECRET_KEY')

if not SECRET_KEY:
SECRET_KEY = "".join(random.choices(string.ascii_lowercase, k=32))
...
# Render Deployment Code
DEBUG = "RENDER" not in os.environ

# Docker HOST
ALLOWED_HOSTS = ["localhost", "127.0.0.1"]

RENDER_EXTERNAL_HOSTNAME = os.environ.get("RENDER_EXTERNAL_HOSTNAME")
if RENDER_EXTERNAL_HOSTNAME:
ALLOWED_HOSTS.append(RENDER_EXTERNAL_HOSTNAME)
...
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware', <-- added
'django.contrib.sessions.middleware.SessionMiddleware',
...
]
...

DB_ENGINE = os.getenv("DB_ENGINE", None)
DB_USERNAME = os.getenv("DB_USERNAME", None)
DB_PASS = os.getenv("DB_PASS", None)
DB_HOST = os.getenv("DB_HOST", None)
DB_PORT = os.getenv("DB_PORT", None)
DB_NAME = os.getenv("DB_NAME", None)

if DB_ENGINE and DB_NAME and DB_USERNAME:
DATABASES = {
"default": {
"ENGINE": "django.db.backends." + DB_ENGINE,
"NAME": DB_NAME,
"USER": DB_USERNAME,
"PASSWORD": DB_PASS,
"HOST": DB_HOST,
"PORT": DB_PORT,
},
}
else:
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": "db.sqlite3",
}
}
...

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles")
...

The changes made above combine the configuration for Docker and deploying on render. The SECRET_KEY is either gotten as an environmental variable or it is generated using the random module. DEBUG is set to False when the project is executed on the render environment. ALLOWED_HOSTS is not applied while debug mode is on or when the tests are run. Once DEBUG is set to False, you will have to add your domain/host to this setting to allow it to serve your Django site. whitenoise was added as middleware to allow Django to recognize and utilize it. The database is decided based on environmental variables. If they are absent, it uses SQLite3. STATIC_ROOT is the directory that Django copies static files into. Note Different databases require a connector to be installed via pip to allow Python to interact with them.

Run the command below to install gunicorn which is the server the application will run on

(venv) $ pip install gunicorn
  • The command below creates a file that contains your project dependencies
(venv) $ pip freeze > requirements.txt

👉 Deploying Django on Render​

  • In the root directory of your application, create a file name build.sh and add the following line
#!/usr/bin/env bash
# exit on error
set -o errexit

pip install -r requirements.txt

python manage.py collectstatic --no-input
python manage.py migrate

if [ -n "$DJANGO_SUPERUSER_USERNAME" ] && [ -n "$DJANGO_SUPERUSER_PASSWORD" ] ; then
python manage.py createsuperuser --no-input
fi
  • Run the command below on your terminal to ensure the script is executable
(venv) $ chmod a+x build.sh
  • Create a new repository on GitHub, initialize the project directory and add the GitHub repository as the remote URL
(venv) $ git init -b main
(venv) $ git remote add origin <link-to-github-repo>
(venv) $ git add .
(venv) $ git commit -m "<COMMIT-MESSAGE>"
(venv) $ git push origin main
  • Create an account with Render and create a new Web Service
  • Select Python for the environment and set the following properties
PROPERTYVALUE
Build Command./build.sh
Start Commandgunicorn core.wsgi:application

*Add the following environmental variables under Advanced

KEYVALUE
SECRET_KEYClick Generate to get a secure random value
DJANGO_SUPERUSER_EMAILsuperuser-email
DJANGO_SUPERUSER_USERNAMEsuperuser-username
DJANGO_SUPERUSER_PASSWORDsuperuser-password
  • Save the web service and deploy the application on Render

👉 Running Django project on Docker​

The following steps will help you create a docker image and start up a docker container for your Django project

Create a file .dockerignore in the root directory with the following content

venv/
.gitignore
db.sqlite3

This ensures that docker does not include these files and folders when copying our application code.

Create a file named Dockerfile in the root folder of your project and add the following commands inside

FROM python:3.10-alpine

COPY . /app/

WORKDIR /app

ENV DJANGO_SUPERUSER_USERNAME=<superuser-username>
ENV DJANGO_SUPERUSER_PASSWORD=<superuser-password>
ENV DJANGO_SUPERUSER_EMAIL=<superuser-email>

RUN pip install -r requirements.txt

RUN python manage.py collectstatic --no-input
RUN python manage.py migrate
RUN python manage.py createsuperuser --no-input

EXPOSE 8000

CMD ["gunicorn", "core.wsgi:application", "--bind", "0.0.0.0:8000"]

This uses a python base image and copies the application code into the app folder in our docker container. The ENV command creates environmental variables, these variables can be overwritten when building the docker container.

Run the command below on your terminal

(venv) $ docker build -t django-app:1.0

This creates the docker image for our application. Using the command docker images will show all images that are present in the device.

The command below will start up the application inside docker and allow us to access the application from port 8000 by binding port 8000 of the local machine.

(venv) $ docker run -d -p 8000:8000 django-app:1.0

With your web browser, open 127.0.0.1:8000 or localhost:8000 to see your web application.


✅ In Summary​

In this Django tutorial, we have covered several concepts related to building web applications with Django, including using pre-designed templates, deploying projects to production, and containerizing applications with Docker.

We began by discussing pre-designed templates, which can help you quickly set up and style your website without the need for a graphic designer.

Next, we covered deploying a Django project to a production environment, which is a critical step in the development process. We demonstrated how to deploy your app to Render using tools like Gunicorn.

Finally, we explored how to containerize a Django application using Docker, a popular tool for creating, deploying, and managing containers. We showed how to create a Docker container for a Django app.

By the end of this tutorial, you should have a good understanding of several important concepts related to building and deploying Django applications. Whether you are building a small web app or a large-scale enterprise application, the tools and techniques we've covered should help you build better and more maintainable software.

✅ Resources​