Django For Beginners
A comprehensive introduction to Django for beginners
This tutorial aims to help beginners getting started with Django, a popular Web Framework written in Python. To get maximum from this content, the audience should be familiar with a terminal and have a minimal set of tools already installed. Python3, a modern code editor (VsCode, Atom), and GIT versioning command-line tool should be enough to experiment with all the code.

Install Python

The core of dependency for Django is Python and we should install the interpreter first. Most of the systems come with Python already installed and we can easily check in the terminal:
1
$ python --version
2
Python 3.8.4 <-- All Good
Copied!
If the version displayed in the terminal is Python2, please note that this version has been discontinued for versioning and development since Jan.2020. To download and install Python access the official page, select the installer that matches the operating system, and follow the installation setup. Once the process is finished, recheck the Python version in the terminal.

Manage Dependencies

With Python up and running, we can install Django and other modules required by our development. The recommended way to install and manage the dependencies for a Python project is to use a virtual environment, a safe way to isolate the dependencies across multiple projects.
1
$ # Linux-based systems
2
$ virtualenv env
3
$ source env/bin/activate
Copied!
For Windows-based systems, the syntax is slightly different:
1
$ virtualenv env
2
$ .\env\Scripts\activate
Copied!
Let's install Django, using PIP (official package manager for Python)
1
$ pip install django
Copied!
The above command will install the latest stable version of Django. From this point, we can use all tools provided by Django to create a new project, apps and manage the project via Django CLI.

Install a Code Editor

This section has plenty of options from the old-school (yet modern) Vim to VsCode and Atom. For those unfamiliar with any of these tools, VsCode might be a good choice to get started fast.
Programming Kit - VSCode editor.

Build a Django Project

A new project can be generated with ease in Django by using django-admin that provides a collection of settings for the database, Django, and security layer.
Create the project folder
1
$ mkdir my-django-project
2
$ cd my-django-project
Copied!
Inside the directory, we will generate the core of our project using django-admin tool :
1
$ django-admin startproject config .
Copied!
Note: Take into account that . at the end of the command.
Create the database and the app tables
1
$ python manage.py makemigrations
2
$ python manage.py migrate
Copied!
Start the application
1
$ python manage.py runserver
2
$
3
$ # Access the web app in browser: http://127.0.0.1:8000/
Copied!
At this point we should see the default Django page in the browser:
Django - Default Project Page.

Create New Application

In the previous section, we've generated the core of the project that handles the configuration and now we will create the first Django application to serve a simple page to the users.
1
$ python manage.py startapp app
Copied!
Add a new route - edit app/views.py
1
from django.shortcuts import render
2
from django.http import HttpResponse # <-- NEW
3
​
4
def hello(request): # <-- NEW
5
return HttpResponse("Hello Django") # <-- NEW
Copied!
The next step is to inform Django that we've created a new app and update the routing to include the new definition.
Update the configuration to include the new app - core/settings.py
1
# File: config/settings.py (partial content)
2
...
3
INSTALLED_APPS = [
4
'django.contrib.admin',
5
'django.contrib.auth',
6
'django.contrib.contenttypes',
7
'django.contrib.sessions',
8
'django.contrib.messages',
9
'django.contrib.staticfiles',
10
'app' # <-- NEW
11
]
12
...
Copied!
Update the routing rules as below - core/urls.py
1
# File: config/urls.py (partial content)
2
...
3
from django.contrib import admin
4
from django.urls import path
5
from django.conf.urls import include, url # <-- NEW
6
from app.views import hello # <-- NEW
7
​
8
urlpatterns = [
9
path('admin/', admin.site.urls),
10
url('', hello), # <-- NEW
11
]
Copied!
After saving all changes we should no longer see the Django default page (the one with the green rocket):
Django For Beginners - The first page.

Create New Model

Even simple applications require minimal storage for persistent data. Django provides out-of-the-box an SQLite database, just to help us start fast. During this section, we will create and interact with a new table (model).
Visualize the default SQL settings - config/settings.py
1
# File: config/settings.py (partial content)
2
...
3
DATABASES = {
4
'default': {
5
'ENGINE': 'django.db.backends.sqlite3',
6
'NAME': BASE_DIR / 'db.sqlite3',
7
}
8
}
9
...
Copied!
The ENGINE specify the technology used to manage the database. In our case is a lightweight (yet powerful) SQLite engine. NAME informs Django where to save the database on the filesystem.
Define a new model Books in sample application. The below changes should be added to sample/models.py:
1
# File: sample/models.py
2
​
3
from django.db import models
4
​
5
class Book(models.Model): # <- NEW
6
title = models.CharField(max_length=100) # <- NEW
7
author = models.CharField(max_length=100) # <- NEW
8
publication_date = models.DateField() # <- NEW
Copied!
Tip - for a quick check over the latest changes we can run check subcommand.
1
$ python manage.py check
2
System check identified no issues (0 silenced).
Copied!
Generate the SQL code (migrate the database).
1
$ python manage.py makemigrations # generate the SQL code
2
Migrations for 'sample':
3
sample\migrations\0001_initial.py
4
- Create model Book
Copied!
Apply changes on the database
1
$ python manage.py migrate
2
Operations to perform:
3
Apply all migrations: admin, auth, contenttypes, sample, sessions
4
Running migrations:
5
Applying sample.0001_initial... OK
Copied!
Use the model via CLI
Once the model is created we can use it via the Django shell:
1
$ python manage.py shell
2
>>>
3
>>> from sample.models import Book # import the Book model in our context
4
>>> from django.utils import timezone # used to provide the value for publication_date
5
>>>
6
>>> book1 = Book(title='The Adventures of Tom Sawyer', author='Mark Twain', publication_date=timezone.now() )
7
>>> book1.save() # save the new book
8
​
Copied!
List all items (books) (using the CLI)
1
$ python manage.py shell
2
>>>
3
>>> from sample.models import Book
4
>>> Book.objects.all()
5
<QuerySet [<Book: Book object (1)>]>
Copied!
We can see our new book returned by the query. Let's improve the information that describes the object.
Django Model - add text representation of an object
To achieve this goal, we should define the __str__() method for the Book model
1
# File: sample/models.py
2
​
3
from django.db import models
4
​
5
class Book(models.Model):
6
title = models.CharField(max_length=100)
7
author = models.CharField(max_length=100)
8
publication_date = models.DateField()
9
​
10
def __str__(self): # <- NEW
11
return self.title # <- NEW
12
​
Copied!
Let's restart the Django console and check the results:
1
$ python manage.py shell
2
>>>
3
>>> from sample.models import Book
4
>>> Book.objects.all()
5
<QuerySet [<Book: The Adventures of Tom Sawyer>]>
6
​
Copied!

​

Using Admin Section

Django comes by default with a usable admin dashboard that allows us to manage all app models and users with ease. In order to access the module, a superuser should be created using the Django CLI:
Create Django Superuser
1
$ python manage.py createsuperuser
2
sername (leave blank to use 'test'): admin
3
Email address: [email protected].us
4
Password: ********
5
Password (again): ********
6
Superuser created successfully.
Copied!
Django Admin - Default View.
CRUD (create, read, update, delete) actions are provided for all default models (users, groups) shipped by Django. To register the new models, Books in our case, we need just a few lines of code.
Register Book model to be visible in the admin section
1
# File: sample/admin.py
2
​
3
from django.contrib import admin
4
​
5
from .models import Book # <- NEW
6
​
7
admin.site.register(Book) # <- NEW
Copied!
After this small change in our code, we should see Books model listed in the admin page:
Django Admin - Register Books Model.
Django Admin - Edit Book Items
Django Admin - Edit Book Item.
​
Thanks for reading! For more topics, feel free to contact Appseed.
​

Resources

Last modified 3mo ago