Django Tutorial: The Ultimate Guide (2023)

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

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.”

Django Tutorial: The Ultimate Guide (2023)

Chapter 1: Django Complete Overview

In this chapter, we will explore the complete overview of Django. Exploring what Djanjo is all about, the features of Django and why you should learn Django as a Python Backend Engineer.

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

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.

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.

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

In this chapter, we will deep-dive into the Django framework. We will explore "The Django way" and learn the architectural patterns that governs Django

The chapter will set pace for the next chapter. Therefore, we recommend that you spend sometime understanding the patterns and philosophies of Django.

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

request response

Chapter 3: Build a Todo Web App with Django

In this chapter, we will build a simple Todo application by implementing the knowledge we have gathered from previous chapters.

This is to help us get ready for real world project which might be 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

unnamed.jpeg

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.

djangofolder.jpeg

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:

djangowithapp.jpeg

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.

djanginit.jpeg

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.

migrationdjango.jpeg

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.

djangofiles.jpeg

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.

DjangoTodoApp.jpeg

Conclusion: Django

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

Whenever you're ready

There are 4 ways we can help you become a great backend engineer:

The MB Platform

Join 1000+ backend engineers learning backend engineering. Build real-world backend projects, learn from expert-vetted courses and roadmaps, track your learnings and set schedules, and solve backend engineering tasks, exercises, and challenges.

The MB Academy

The “MB Academy” is a 6-month intensive Advanced Backend Engineering BootCamp to produce great backend engineers.

Join Backend Weekly

If you like post like this, you will absolutely enjoy our exclusive weekly newsletter, Sharing exclusive backend engineering resources to help you become a great Backend Engineer.

Get Backend Jobs

Find over 2,000+ Tailored International Remote Backend Jobs or Reach 50,000+ backend engineers on the #1 Backend Engineering Job Board

Backend Tips, Every week