Django Tutorial: The Ultimate Guide (2021)

Kingsley Ihemere
15 min readSep 8, 2021

This is the most comprehensive tutorial on the Django framework online.

High scalability, versatility, security, rapid development, well-structured and detailed documentation are some features that make the Django framework one of the best and most consistent web frameworks in the industry.

With Django, there is only one way to do things, “The Django Way”.

Yes, Django is built to force you to follow industry-standard ways of developing web applications.

The advantage this has is that working with Django will make you a better developer.

The downside is that it doesn’t give room for some flexibility with the sister framework Flask.

This Django tutorial will teach the Django framework by building a basic Todo web application that can Create, Read, Update and Delete, otherwise called “CRUD.”

To learn Django in detail, there is no better course to recommend personally than Full stack web development and AI with Python (Django). Check it out now for a discount.

Prerequisites

Before continuing with this guide, you will need to understand server-side web programming, frameworks, general Knowledge of Python, which will aid your understanding of the Django framework.

To learn Python and Django in detail, there is no better course to recommend personally than Python Django 2021 — Complete Course. Check it out now for a discount.

Outline

Below are the sections:

  1. Django Complete Overview
  2. The Django Framework (Introducing MVT)
  3. Build a Todo Web App with Django
  4. Deployment To Heroku

Chapter 1: The Overview

In this Django tutorial, we will hold you by the hands and walk you through installing Django, setting up database connections with MySQL, creating a complete CRUD application, and deploying to Heroku.

So grab a cup of coffee and join us on this beautiful and smooth ride.

What is Django

Django is a high-level open-source Python MVT web framework that enables the rapid development of secure and maintainable web applications.

Django follows the popular MVC (Model View Controller) architecture with a bit of variation. While MVC stands for Model View Controller, Django’s MVT stands for Model View Template.

When it comes to using Django as a framework of choice, there is only one way to do things, “The Django Way.” It supports an industry standardized way of developing robust web applications.

Features of Django

Before making any framework your choice for a project, you must have studied it and be satisfied with its features. Django is a framework with vibrant and attractive features. Let’s explore them.

  1. Django’s excellent interactive documentation makes it easy and exciting for any new developer to pick a project and finish it in record time.
  2. Django is a framework built upon Python. Being about the most straightforward programming language with numerous packages and libraries, you can quickly build websites, web apps, data science, machine learning, and artificial intelligence projects using Django and other python packages.
  3. Django is, by default, Search Engine Optimized.
  4. It is Highly Scalable. The Instagram team that developed the popular Instagram using Django should quickly tell you what you can do with Django.
  5. Django is Versatile
  6. It is highly secured.
  7. With over a decade of solid performance and consistency, it is no joke that Django is thoroughly tested.
  8. Django provides rapid development.
  9. It comes with a prebuilt admin area. This feature means you don’t necessarily need to build a new admin area to manage your web application.

Why you should learn Django

Django, as stated above, follows industry standard best practices for web application and software development. This standard forces you to write clean codes while you learn.

Django works best and easily with SQL databases. With Django, you don’t need to know how to query SQL to create your applications.

As stated earlier, Django is built on Python, which is the language of choice for any Data Science, Data Analytics, Artificial Intelligence, and Machine Learning project.

So, if your application requires ML, AI, Analytics, or Data Science functionalities, you should go with Django.

When learning any language, the importance of community cannot be overemphasized.

Luckily, Django boasts an active community that will help hold you by the hands and make you a professional software developer.

When you want to build complex web applications in less time with the industry’s best practices, Django is the Python framework of choice.

From the somewhat difficult Django 1.0 to today’s simple and elegant looking Django 3.0+, we have seen consistent growth in developing and maintaining the Django framework.

The key features and functionalities that make Django outstanding are:

  • Open Source.
  • It supports the Full Stack Framework.
  • Authentication.
  • URL Routing.
  • Templating Engine.
  • DRY (Don’t Repeat Yourself).
  • ORM Mappers.
  • It provides Database schema migrations for common databases like PostgreSQL, MySQL, SQLite, Oracle under the third-party drivers.
  • A Variation of MVC Architecture called MVT
  • Inbuilt Admin Panel
  • Excellent and Fast debugger interface
  • ASGI (Asynchronous Server Gateway Interface) and WSGI (Web Server Gateway Interface compliant in Django 3.0+

Wow! You now have a complete overview of what Django stands for and the things you can do with it.

You can pause a little, take a sip of your coffee and follow us as we discuss the Django Framework in more detail.

Chapter 2: The Django Framework

So far, the buzzword here has been “Framework.” But what does framework mean? There is no doubt that we could be using the word without understanding its meaning and why we should use it.

According to Isaac Newton, “If I have seen further, it is by standing on the shoulders of giants.”

This quote by Isaac Newton gives light to how far and powerful frameworks can be. Why reinvent the wheel when you can ride on it and add more functionalities?

Let us elucidate. You want to build a house and need all the necessary timber to start and finish it.

You are faced with two options:

  1. Building from scratch, where you will need to cut down some timbers and shape them to your desired shape and sizes.
  2. Building with already made frameworks of woods of different sizes and save yourself some precious time, energy, and sometimes money.

Django web framework was developed to force you to build industry-standard web applications by providing the framework of woods of different sizes to save you time, energy, and cost while developing your MVP.

In this section, we will discuss the three main parts of the framework. This is called the MVT, which stands for Model View Template.

Are you ready? Please fasten your seatbelt. We will be going for an exciting ride.

What is MVT?

MVT stands for Model View Template. It is a software and design pattern variation of MVC (Model View Controller).

MVC is a standard architectural pattern that many languages employ with slight variations such as Laravel, Ruby on rails, AdonisJS, etc.

The Django framework handles all the controller parts of the MVC by itself. This means Django has done a lot of the heavy lifting for you and helps reduce the code you will need for a minimum viable product (MVP).

This made Django introduce and implement templating as a pattern. Let us briefly discuss them separately.

Model

Models in Django are the single definitive source of information about your data. Generally, each model maps to a single database table. It helps provide the interface for the data stored in the databases.

For instance, assuming we have a Car class in our model, the class name will correspond to the table name in our database. This means we don’t have to create a table in our database manually, but we only run migrations to generate the tables.

View

Definitions for Django views are somewhat not simple to understand.

So we will try explaining it with what it does so that a non-technical person can easily understand it.

Think of this as the file where you write the functions that retrieve data from the database and display it on your website’s templates.

With this explanation of Django views, one can say that it supplies the dynamic content to HTML/CSS/Javascript files and its templating language.

At the same time, the Django template fully represents the static part. Next, let’s discuss the last part of the Django MVT architecture.

Template

As we discussed briefly in view, the Django template represents the static part of your desired output.

Again, to explain this for easy understanding, your template will contain the HTML, CSS, Javascript, and Django templating language.

So while the HTML provides the static structure of your website, the templating language is used to dynamically display data on the HTML file from the view file.

URL Routing: Request and Response Analogy

Chapter 3: Build a Todo Web App with Django

Before we continue with our data analysis application, let us ignite your appetite by building a simple Todo application. This is to help us get ready for our project which is a little bigger

To build a Django application for this Django tutorial, you need to have python installed on your computer. We assume you have it.

It is good practice to develop your application in a virtual environment. We used Virtualenv. The code below will help you install it.

pip install virtualenv

Next is to create a virtual environment.

virtualenv virt source virt/Scripts/activate # this will activate the virtual environment.

The other packages are:

pip install django pip install mysqlclient

Start a Django project using the following command.

django-admin startproject mytodo

Move into the created project with cd mytodo. This is the root directory of your application.

Create Task App

The above image is the structure of a Django project. Now let’s create an app.

python manage.py startapp task

After starting a new app, the new project structure will look this:

Add the app task into your settings.py file.

# Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'task' ]

Database set up

Still on this file, recall we installed mysqlclient earlier, we did because we will be using MySQL for our database.

Now, go to your PHPMyAdmin or any database client of your choice, create your database.

DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'todoapplication', 'USER': 'root', 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT': '3306', } }

It is time to create our model. Let’s go to our task folder and open Models.py and paste the code below.

from django.db import models # Create your models here. class Task(models.Model): title = models.CharField(max_length=200) completed = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title

This is a simple model with a class name “Task”. It has three attributes and a method.

The title of the todo task, a boolean field “completed” and created time.

The method is used to display the title in the admin panel of the app.

Everything is looking good. Let’s make the migration. This will help make successful connections to the database and create tables with the prebuilt Django models and our model.

Before we make the initial migration, it is important to see that the migration folder and the __init__.py is empty.

Run this command to create migrations for your database:

python manage.py makemigration

This will display all the files available for migrations where there are no changes, it will indicate so.

When you make migrations, Django prepares a migration file for you as above,

Run this command to migrate your database:

python manage.py migrate

Create Task Files

Go to the task folder and create the following folders "templates", inside the templates folder create "task". Then create the following HTML files.

Open the views.py file in the task folder and paste this code below:

#views.py from django.shortcuts import render, redirect from django.http import HttpResponse from .models import * from .forms import * # Create your views here. def index(request): tasks = Task.objects.all() form = TaskForm() if request.method == 'POST': form = TaskForm(request.POST) if form.is_valid(): form.save() return redirect('/') context = {'tasks': tasks, 'form': form} return render(request, 'task/list.html', context) def updatingTask(request, pk): task = Task.objects.get(id=pk) form = TaskForm(instance=task) if request.method == 'POST': form = TaskForm(request.POST, instance=task) if form.is_valid(): form.save() return redirect('/') context = {'form': form} return render(request, 'task/update.html', context) def deleteTask(request, pk): item = Task.objects.get(id=pk) if request.method == 'POST': item.delete() return redirect('/') context = {'item': item} return render(request, 'task/delete.html', context)

Next is the urls.py, but the app doesn't come with a urls.py, this is because we can do all our routing in the project's urls.py or we can create a new one for the task folder. Let's create it:

# task.urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='list'), path('update/<str:pk>/', views.updatingTask, name='update'), path('delete/<str:pk>/', views.deleteTask, name='delete'), ]

For the Django project to see it, it will need to be routed to the project’s URLs. Let’s do that:

# urls.py from django.contrib import admin from django.urls import path from django.urls.conf import include urlpatterns = [ path('admin/', admin.site.urls), path('', include('task.urls')) ]

Here, we just imported the module name include to help us include the app URLs.

Next, Let us create form.py:

from django import forms from django.forms import ModelForm from .models import * class TaskForm(forms.ModelForm): class Meta: model = Task fields = '__all__'

Register the model to your admin.py:

from django.contrib import admin from .models import Task # Register your models here. admin.site.register(Task)

The last path is our HTML files:

List.html

# list.html <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css" /> <style> body { width: fit-content; margin: 20px auto; } </style> <div> <h3>Todos</h3> <form method="POST" action="/" class="ui form"> <div class="ui field action input" style="width: 525px;"> {% csrf_token %} {{form.title}} {% if form.title %} <input type="submit" name="Create Task" class="ui primary button" /> {% else %} <input type="submit" name="Update Task" class="ui primary basic button" /> {{ form.complete }} {% endif %} </div> </form> {% for task in tasks %} <div class="ui segment" style="width: 600px;"> {% if task.complete == True %} <strike>{{ task }}</strike> {% else %} <p>{{task}}</p> {% endif %} <div class="right-align"> <a href="{% url 'update' task.id %}" class="ui secondary basic button ">Update</a> <a href="{% url 'delete' task.id %}" class="ui negative basic button right hide-on-med-and-down">Delete</a> </div> </div> </div> {% endfor %} </div>

Update.html

Next, let’s update the update.html by pasting the following code:

# update.html <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css" /> <style> body { width: fit-content; margin: 20px auto; } form { margin: 0 5px; } </style> <h3>Update Task</h3> <form method="POST" action="" class="ui form"> <div class=" ui field action input"> {% csrf_token %} {{ form }} <input type="submit" name="Update Task" class="ui primary basic button" /> </div> </form>

Delete.html

Lastly, let’s update the detele.html by pasting the following code:

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css" /> <style> body { width: fit-content; margin: 50px auto; } form { float: right; } </style> <p class=" container">Are you sure you want to delete " {{item}}"?</p> <div> <a href="{% url 'list' %}" class="ui secondary basic button">Cancel</a> <form method="POST" action=""> {% csrf_token %} <input type="submit" name="Confirm" class="ui negative basic button" /> </form> </div>

Everything is fine, let’s run our migration:

python manage.py migrate

Testing the app

And also start the development server with this command:

python manage.py runserver

Your app should be running on http://127.0.0.1:8000/. If you visit the URL, you should be presented with the webpage below, if you set up everything correctly.

Chapter 4: Deploying To Heroku

Heroku is a cloud service-providing company that supports many web frameworks.

We are choosing Heroku because it allows for free hosting for the deployment of small applications.

This is ideal for small applications. If you decide to scale your app, you can go straight to paid services.

To use Heroku, we need to download the Heroku toolbelt. Click here to download it, install and restart your terminal. Then navigate to your project root folder.

Type in heroku -version to check if your installation was successful.

Next is to make some changes to our application. First, remember we downloaded some libraries at the beginning.

Now we need to create a Procfile. Go to the root folder and create it.

touch Procfile

Open it and type this:

web: gunicorn richestmen.wsgi

This is the name of our project. Save and close it. Still, create a requirements.txt file(if you have not created it). This file will create a list of all installed libraries.

Pip freeze > requirements.txt

Let’s head to settings.py to do some major changes. Scroll down to MIDDLEWARE and add whitenoise to the list of middleware.

Then scroll down to the bottom of the settings.py file and add whitenoise as the staticfile storage. Whitenoise takes care of the static files.

We avoided using static files (CSS/Javascripts/Images) in this project, but we will show you how to include them in the settings.py.

Lastly, in the settings.py file, add this line of code as the last code. This will activate Django-Heroku

django_heroku.settings(locals())

Please, in the same settings.py, scroll to where you will find

Set it to

DEBUG = False

Before we log in to Heroku, we need to push to GitHub. Log in to your GitHub account, create a repository for this application and push your app to GitHub.

In your terminal, type:

heroku login

Follow the prompt and login, then come back to your terminal (CTRL+C to continue)

heroku create myrichestmen <Any name of your choice>

That is the name we gave the application. You can now view the application in your Heroku account.

git push heroku master # this command will push the code from your master branch of your git to the Heroku remote.

We need to copy the URL of the application from the terminal or the Heroku settings.

Then go to our settings.py, go to ALLOW_HOSTS and add the URL link to the list of URLs allowed to access your website.

Also, import the following files:

Import os Import django_heroku

The last reconfiguration here is the one in your database connection. Remember we are working with localhost.

Since we are deploying, we need to create a MySQL database in Heroku and change the database detail in our settings.py before deploying.

Let’s do that:

Login to your Heroku account through the browser, click on the app you created,

Click on the Resources tab, search for ClearDB. It is an add-on that helps you install and use MySQL with your app in Heroku.

Choose ignite, which is the free MySQL database. Heroku will request your credit card. They will not charge you until you upgrade to paid services.

Click on the clearDB MySQL, and it will open up a new window. Click on the circled link.

This is for you to see that it’s created. Next, go back to Heroku, click on Settings.

Then Config Vars will reveal your MySQL database information.

Click and copy the information above the VALUE and follow the illustration in the diagram below.

Hmmm!

Don’t worry. We are almost there. Save and close your file. In your terminal:

git add . git commit -m "database updated" git push heroku master

This will update your application online. Now we need to migrate our application to the database.

heroku run python manage.py migrate

Type heroku open to open your application.

Reference Links:

Django with Data Sciencehttps://devcenter.heroku.com/articles/heroku-clihttps://docs.djangoproject.com/en/3.2/https://devcenter.heroku.com/articles/cleardbhttps://www.chartjs.org/docs/latest/Step by Step Guide for Deploying a Django Application using Heroku for Free

Conclusion

This Django tutorial explains the fundamentals of creating an application with Django using Django function-based views, MySQL database, and deployed to Heroku.

This is just the basics of Django. There are so many, and no better place to go than Django’s official documentation.

To learn Django in detail, there is no better course to recommend personally than Full stack web development and AI with Python (Django). Check it out now for a discount.

Let us know in the comment if you have any challenges, and we will fix them together.

Thank you

Finished app https://dekingstodo.herokuapp.com/

Github repo: https://github.com/dekings44/billionaire

LinkedIn: www.linkedin.com/in/realdekings

Twitter: @RealDekings

Medium: https://dekings.medium.com/

Originally published at https://masteringbackend.com on September 8, 2021.

--

--

Kingsley Ihemere

A Data Analyst/Data Engineer, I build and analyze with Python(Django & FastAPI), JavaScripts(Vue.js), SQL, Excel, Google Cloud Platform, Power BI & Tableau.