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.”
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.”
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.
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.
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.
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.
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:
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.
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:
Building from scratch, where you will need to cut down some timbers and shape them to your desired shape and sizes.
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.
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.
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.
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.
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
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
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.
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'
]
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
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
<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>
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>
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
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.
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
There are 4 ways we can help you become a great backend engineer:
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” is a 6-month intensive Advanced Backend Engineering BootCamp to produce great backend engineers.
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.
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
Backend Tips, Every week