Codementor Events

Getting Started with Django - Tutorial for beginners

Published Jun 21, 2021
Getting Started with Django - Tutorial for beginners

Hello Coders,

This article aims to help beginners to learn faster and easier how to code simple and useful things using Django for the server side. For complete newcomers, Django is a popular web framework designed and actively supported by experinced developers acrossthe globe. Using Django we can code from simple one-page websites to complex APIs and eCommerce solutions.

Thanks for reading! For support or updates, AMA in the comments section. Topics coverd by this article:

  • Set up PC for Django
  • Create a new Django project
  • Create a new Django app and code our first (simple) page
  • Create a new model and use it in the Django CLI
  • Admin Section - create a Django superuser
  • Django Authentication System - let's manage users with ease

NOTE: Based on the audience feedback, this tutorial will be periodicaly updated.


Set up PC for Django

Django is written in Python Programming Language and to use all the magic provided by Django, we need to have Python3 properl installed in our workstation. Most of the modern operating system come with Python preinstalled. For those that aren't sure about this, please open a terminal window and type python:

$ python --version
Python 3.8.4       <-- All Good     

If the version is Python2 it might be a good move to update to Python3. The version 2 is a legacy version without active support.

To install or update Python, please access the official download page, download the version that matches your operating system and execute the installer. Once the installation process is finished, open the terminal and re-check the installed version.


Manage Django Installation

The recommended way, even for beginners, is to use a virtual environment a sandboxed execution environment that helps us to isolate Python dependencies across multiple projects.

Create a virtual environment - Linux-based OSs (including MacOS)

$ virtualenv env
$ source env/bin/activate  

For Windows-based systems, the syntax is different

$ virtualenv env
$ .\env\Scripts\activate

Once our environment is up & running, the next step is to install Django.

$ pip install django

The above command uses PIP, the official package manager for Python, to install the latest version of Django. To install a specific version, please use the syntax:

$ pip install "django==2.2.10"

After the installation is complete, we can check the version using the Python console:

(env) $ python 
(env) >>> import django
(env) >>> django.__version__
(env) '2.2.10'

Create 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, and security layer.

Create the project folder

$ mkdir django-for-beginners
$ cd django-for-beginners

Inside the directory, we will generate the core of our project using django-admin tool:

$ django-admin startproject config . 

Set up the database

$ python manage.py makemigrations
$ python manage.py migrate

Start the project

$ python manage.py runserver 
$
$ # Access the web app in browser: http://127.0.0.1:8000/

By default, Django starts projects using the PORT : 8000. In case this port is already taken, we can use another one:

$ python manage.py runserver 8005

The above instruction will start the project on port 8005.


Create New Application

At this point we have all the Django magic at our disposal and we can start coding something simple: a Hello World page. Let's go!

$ python manage.py startapp app

Add a new route - edit app/views.py

from django.shortcuts import render
from django.http import HttpResponse     # <-- NEW

def hello(request):                      # <-- NEW    
    return HttpResponse("Hello Django")  # <-- NEW   

The next step is to update the project configuration and inform Django that we've created a new app.

Update the project configuration - config/settings.py

# File: config/settings.py (partial content)
...
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app'                           # <-- NEW
]
...

Update the routing rules - config/urls.py

# File: config/urls.py (partial content)
...
from django.contrib import admin
from django.urls import path
from django.conf.urls import include, url   # <-- NEW
from app.views import hello                 # <-- NEW

urlpatterns = [
    path('admin/', admin.site.urls),
    url('', hello),                         # <-- NEW
]

After saving all changes we should no longer see the Django default page:

Django Tutorial for Beginners - Simple Hello World.


Create a new Model

Even simple applications require minimal storage for persistent data like registered users, a newsletter subscription or any other service that requires to remember something. Before we start, might be a good idea to visialize the database settings provided by default in Django:

Default SQL settings in Django - config/settings.py

# File: config/settings.py (partial content)
...
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}
... 

The ENGINE specifies the technology used to manage the database. In our case is a lightweight 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 app/models.py:

# File: sample/models.py

from django.db import models                       

class Book(models.Model):                                 # <- NEW
    title            = models.CharField(max_length=100)   # <- NEW 
    author           = models.CharField(max_length=100)   # <- NEW
    publication_date = models.DateField()                 # <- NEW 

Once the file is saved we need to run a database migration that consist in two phases: generate the SQL and apply the changes on the database:

Phase #1 - Generate the SQL code - execute makemigrations subcommand

$ python manage.py makemigrations  
Migrations for 'sample':
  sample\migrations\0001_initial.py
    - Create model Book 

Phase #2 - Apply the changes on database

$ python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sample, sessions
Running migrations:
  Applying sample.0001_initial... OK 

Let's interact with our newly created model via Django CLI

$ python manage.py shell
>>> 
>>> from sample.models import Book     # import the Book model in our context
>>> from django.utils import timezone  # used to provide the value for publication_date
>>>
>>> book1 = Book(title='The Adventures of Tom Sawyer', author='Mark Twain', publication_date=timezone.now() )
>>> book1.save()                       # save the new book

List all items - using the Django CLI

$ python manage.py shell
>>> 
>>> from sample.models import Book
>>> Book.objects.all()
<QuerySet [<Book: Book object (1)>]>

The new Book object is listed and available for editing.


Django 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:

$ python manage.py createsuperuser
sername (leave blank to use 'test'): admin
Email address: test@appseed.us
Password: ********
Password (again): ********
Superuser created successfully. 

The createsuperuser superuser does the hard work for us and now we can access the admin section using for the login the same credentials provided as input for createsuperuser subcommand.

Django For Beginners - Default Admin Section page.

The default vew includes only the default Django tables (Users and Groups) but we can register with ease any other model defined in the project with a single line:

Register Book model in the admin section

# File: app/admin.py

from django.contrib import admin

from .models import Book        # <- NEW
admin.site.register(Book)       # <- NEW 

Django for Beginners - Book Model is now visible in the admin section.

Book Model Items - Item edit option

Django for Beginners - Book Model Items supports editing.


Django Authentication System

Being a "batteries-included" framework, Django comes with a powerful authentication/authorization system that we can use and extend in our projects without much effort. In this tutorial we've used already the authentication system when the superuser was created.

User Model

The User model represents the core entity used to save and manage authentication in Django. This table (model) is provided by Django core system with following properties:

  • username: Mandatory Field
  • password: Mandatory Field
  • email: optional, but recommended
  • first_name: optional
  • last_name: optional

The most simple way to create a new user is probably via the terminal and Django shell:

$ python manage.py shell
>>> 
>>> from django.contrib.auth.models import User
>>> user = User.objects.create_user('test', 'test@whatever.com', 'S3cret_PASS')

As we can see, Django makes this task super trivial. Event the password hashing is covered and we can use plain text passwords during the creation process, without worring about the password alghorithm.

List all registered users

>>> User.objects.all()         
<QuerySet [<User: admin>, <User: test>]>

Thank you for reading this long post. For more resources, please access:

Django For Beginners - Pixel Lite, open-source Django Starter provided by AppSeed.

Discover and read more posts from Adi Chirilov - Sm0ke
get started
post commentsBe the first to share your opinion
Show more replies