Getting Started with Django with Python – Easy Tutorial

getting-started-with-django-in-python-step-by-step-tutorial

In this tutorial, step by step I will show you how you can learn and get started with Django, in the easiest way.

When I started learning Django framework of Python, I struggle a lot to find the correct and easiest path. Django is a complex and tidy framework. Here you need to maintain specific format for all different components.

So if you start learning Django from somewhere else, you will be lost and end up learning nothing. There should be a proper roadmap to learn Django.

This is the reason I started this series of Django tutorial, so that I can share you the best path and method to learn Django which I realized after spending months of struggling.

Objective of this Tutorial

In this tutorial, I will show you how you can get started with Django by creating a simple web application. Most important thing is that you need to understand each components of this framework.

In this application I want to display name and age of list of students from a database. The database I am going to use in this basic Django project is Sqlite. This Sqlite database comes by default with Django framework, so I am going to use that.

Getting Started with First Django Project

Okay let’s now understand Django framework by doing this simple project (display student name and age). For better explaination I will break entire learning (developing the project) into some steps. Let’s get started.

Step1: Setting Up Development Environment

As you already know Django is a Python backend framework to develop web application. So to work with Django you must have Python installed in your system.

I personally prefer Anaconda for my day to day data science and analysis work. While writing this tutorial also I am using Anaconda for Python. But don’t worry, you will get same result if you are using standard Python.

Once your system is ready, you can download and install Django using below pip command.

pip install django

Step2: Create a Django Project

In Django framework, a “project” is like a big container for your web applications. There can be multiple applictions under one project. For example, let’s say you are working on a helth application “project“. Now under this health project there can be multiple applications like: Stopwatch, Calorie counter, BMI calculator, Food recommendation, etc.

To create a new Django project, open your command prompt or terminal and run the below command.

django-admin startproject first_django_project

Here, first_django_project is my Django project name. You can change this name as per your wish.

pip-install-django-and-create-project

In the screenshot, my rood directory name was “django tutorial“. So don’t get confused with that name. It’s just a folder name.

After running above command, a new folder will get created inside your working directory. Inside that folder another folder will be there with the same name along with that, there should be a Python file named manage.py. So now your folder structure should look like below:

Woking directory (django tutorial)
    └── first_django_project
           β”œβ”€β”€ manage.py
            └── first_django_project
                  β”œβ”€β”€ __init__.py
                    β”œβ”€β”€ asgi.py
                    β”œβ”€β”€ settings.py
                    β”œβ”€β”€ urls.py
                  └── wsgi.py

As you can see in the above folder structure, inside our working directory and project folder some python files got created. Give me some moment to tell you use of those files.

manage.py

manage.py is a command-line tool in Django. This Python file simplifies various development tasks such as starting the server, creating new apps, managing database migrations, setting up admin superusers, running tests, executing custom commands, streamlining the development process, etc.

__init__.py

In Django project, you’ll find __init__.py files in various directories, such as the main project folder and individual app folders. It is used to organize and structure of the Django project and help Python understand how to treat the directories as packages or modules.

asgi.py

asgi.py file is most important when you deploy any Django application. It is typically located in the project’s main directory, alongside the settings.py file. It is used to point to the ASGI (Asynchronous Server Gateway Interface) application instance that will handle asynchronous tasks.

Comming back to the main part of our Django tutorial. As you can understand, you can create multiple Django projects with above command. Now to work with a specific project (in our case our newly created project), we need to go inside that project folder. Just run below command to go inside that project directory.

cd first_django_project

Step3: Create a Django App

As I said, in Django there can be multiple applications for a single project. In this example, let’s create an app to show student information (Name and Age). To create an app for a Django project run the below command.

python manage.py startapp student_info

Note: In Step2, we are already inside first_django_project directory. That means we are creating this student_info app for first_django_project project.

Also Read:  Python | List all files in a Directory

Once you run the above command, a folder will be created inside your working directory. Name of that folder is same with your app name. So now my folder structure looks like below:

Woking directory (django tutorial)
    └── first_django_project
           β”œβ”€β”€ manage.py
            └── first_django_project
           β”‚       β”œβ”€β”€ __init__.py
             β”‚       β”œβ”€β”€ asgi.py
             β”‚       β”œβ”€β”€ settings.py
             β”‚       β”œβ”€β”€ urls.py
           β”‚       └── wsgi.py
           └── student_info
                   β”œβ”€β”€ __init__.py
                     β”œβ”€β”€ admin.py
                     β”œβ”€β”€ apps.py
                     β”œβ”€β”€ models.py
                     β”œβ”€β”€ tests.py
                   β”œβ”€β”€ views.py
                     └── migrations
                           └── __init__.py

As you can see in the above folder structure, inside our app folder (student_info) some Python files and one another folder (migrations) got created.

Step4: Add App to Installed Apps

Once you create the application, you need to add that application to Django default installed apps list. To do that open setting.py from your project folder (Wording Directory\first_django_project\first_django_project\setting.py) and update INSTALLED_APPS variable by adding your newly created app name to that list.

By default, it looked like this:

INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
]

After update, it looks like this:

INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "student_info"
]

That’s it. Save the settings.py file. I did not find any automated way to add that app name. So I do it manually every time I create a new app for a specific Django project.

While in the settings.py file let’s have a look at some other important configurations of Django framework.

DEBUG Toolbar Django

In settings.py you will find a line like below:

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

When DEBUG is set to True, it means your application is in debug mode. In this mode, Django provides detailed error pages with stack traces, debug information, and other sensitive details whenever an error occurs. This can be so much helpful while developing you Django application.

When deploying a Django application for production, it’s essential to set DEBUG to False. So that you are not revealing detailed error information in production which can be risky. As it might expose sensitive details about your application, and its setup, and could be exploited by potential attackers.

Secret Key

This key is a critical part of Django’s security and is used for various protective measures. Treat the secret key like a password, store it securely, and avoid sharing it publicly to enhance the security of your Django application in a production environment.

In settings.py file you should find your default secret key like below:

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-tmw7)p)gnhw1^zx97s*jpxe)m)68i=l7w3oc=6u*sza7xca1z3'

Change this and make it unique. So that no one can guess it.

Databases

Default database configuration of you Django project looks like below:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}

This configuration indicates that your Django project will use SQLite as the default database engine, and the database file (db.sqlite3) will be stored in the project’s base directory. If you want to learn about SQLite database read this article: SQLite Python Tutorial with Examples.

It is not mandatory to use SQLite database. You can use any other database in your Django project.

Step5: Create a Model

So we have successfully configured Django framework with Python in our system. Let’s now start writing code for our first Django Application.

Django is a MVT (Model View Template) framework. So it is a good practice to start with Model part then write code for View and finally we should work on Template.

It is not that you can not start from view or template first. But it is a good practice to start with Model first.

In Django, the model helps define how our data looks (structure of our data) and what kind of information we want to use in our web application. In our example, name and age of students.

The porpuse of defining data structure in Model is to make it easy to store and retrieve information in our application. So that everything will be tidy and there can be less chance to mess up anything. This is the speciality of Django framwork among other backend development fromeworks of Python.

So let’s create a Model for our application, inside your app’s folder (student_info) , there is a file called models.py. Open it.

As I explained, in this file, you need to define what kind of data you want to store or use in your application. In our example we want to store information about student. So our models.py will looks like below:

from django.db import models

# Create your models here.
class Student(models.Model):
    name = models.CharField(max_length = 100)
    age = models.IntegerField()

Once pasted above code, save the models.py file. One thing to note, there can be multiple model like Student in models.py.

Also Read:  Flask vs Django: Which One is Easier for Machine Learning?

This model says we want to store student’s names as character and ages in integer field.

Step6: Migrations and Database Setup

Migrations are like instructions to the database, telling it how to create table and fields to store your data.

To make sure your data is stored correctly in a database, you need to run some commands.

First, create a migration with this command:

python manage.py makemigrations

Then, apply this migration to your database using below command:

python manage.py migrate

If you do not execute above two lines of commands, you may get error like: django.db.utils.OperationalError: no such table:

django-commands-to-create-and-migrate-project-model-python

Once you run above two commands, one database file named db.sqlite3 will get created inside your project folder. So now your folder structure should looks like below:

Woking directory (django tutorial)
    └── first_django_project
           β”œβ”€β”€ manage.py
           β”œβ”€β”€ db.sqlite3
            └── first_django_project
           β”‚       β”œβ”€β”€ __init__.py
             β”‚       β”œβ”€β”€ asgi.py
             β”‚       β”œβ”€β”€ settings.py
             β”‚       β”œβ”€β”€ urls.py
           β”‚       └── wsgi.py
           └── student_info
                   β”œβ”€β”€ __init__.py
                     β”œβ”€β”€ admin.py
                     β”œβ”€β”€ apps.py
                     β”œβ”€β”€ models.py
                     β”œβ”€β”€ tests.py
                   β”œβ”€β”€ views.py
                     └── migrations
                           β”œβ”€β”€ __init__.py
                         └── 0001_initial.py

Step 7: Add some data

If you open that db.sqlite3 you can see that that it is a blank database. There is nothing inside this SQLite DB file. In order to show some data to our Django web application or our simple website, we need to add some data to that database. In this example, we need to add student information to that database.

There are mainly two ways to do that :

  1. Insert data in db.sqlite3 using separate Python code: This is the best approach to fill any database automatically.
  2. Insert data from models.py file: This is manual. Just to show you the process, may be for simple application like this tutorial. You should not do this
    in real time large applications.

Since this is a simple application just to get you started with Django, I am filling some data in db.sqlite3 using models.py file itself. To do that, you need to add some line of codes to your models.py. So final models.py file should looks like below:

from django.db import models

# Create your models here.
class Student(models.Model):
    name = models.CharField(max_length = 100)
    age = models.IntegerField()
    
# Add sample data directly
Student.objects.create(name='John Doe', age=20)
Student.objects.create(name='Jane Smith', age=22)

Since we are doing modification to models.py file. again we need to run below commands:

python manage.py makemigrations
python manage.py migrate

Step8: Create a View

Views control what data you want to display on your web pages. View connects your models to your templates.

In your app folder (student_info), there is a file called views.py. Open it and write below code in it.

from django.shortcuts import render
from .models import Student

# Create your views here.
def students(request):
    students_list = Student.objects.all()
    return render(request, 'students.html', {'students': students_list})

In this example, the students view fetches data from the database (using model) and passes it to the template for rendering. It handles the logic of what to show on the web page.

Step9: Create a Template

Template in Django is nothing but a structure and layout of your web pages. In simple words template is a group of HTML, CSS & JavaScript files which are used to develop frontend or client side part of your web application.

In Django, you need to follow a special format to maintain all your template files. You need to create a new folder inside your app’s folder (in my case “student_info“). and name it “templates“. This is the folder where you need to keep all your frontend files (HTML, CSS, JavaScript, etc.) for a specific application.

In this example, I just want to show student information in a very basic HTML page. So I will create an HTML file named “students.html” (you can name it anything) inside the “templates” folder.

So now folder structure of our django project should looks like below:

Woking directory (django tutorial)
    └── first_django_project
           β”œβ”€β”€ manage.py
           β”œβ”€β”€ db.sqlite3
            └── first_django_project
           β”‚       β”œβ”€β”€ __init__.py
             β”‚       β”œβ”€β”€ asgi.py
             β”‚       β”œβ”€β”€ settings.py
             β”‚       β”œβ”€β”€ urls.py
           β”‚       └── wsgi.py
           └── student_info
                   β”œβ”€β”€ __init__.py
                     β”œβ”€β”€ admin.py
                     β”œβ”€β”€ apps.py
                     β”œβ”€β”€ models.py
                     β”œβ”€β”€ tests.py
                   β”œβ”€β”€ views.py
                     └── migrations
                     β”‚     β”œβ”€β”€ __init__.py
                   β”‚     └── 0001_initial.py
                   └──templates
                             └── students.html

In this students.html template file, we design how the data from the view will be presented to user. This way, you can create user-friendly web pages. Below is the code for my students.html file.

<!DOCTYPE html>
<html>
<head>
	<title>Student List</title>
</head>
<body>
	<h1>Student List</h1>
	<ul>
		{% for student in students %}
			<li>{{ student.name }}, Age: {{ student.age }}</li>
		{% endfor %}
	</ul>
</body>
</html>

Step10: Create URL Routing

URL routing is used to map specific web addresses to views in our Django apps. The urls.py file in our app tells Django which view to display when a particular URL is accessed. This helps users navigate to different parts of your web application.

Also Read:  Rename columns in R

Inside our your folder (in our case student_info), create a new file named urls.py. In this file you need to define what web addresses should show your views. Below is the code for urls.py file for this simple application.

from django.urls import path
from . import views

urlpatterns = [
	path('', views.students, name = 'student-list'),
]

In this code, in line 5, I have mentioned the logic to connect view with url path. That line says that when someone goes to our website and adds ‘students/‘ to the URL, they will see the “students” view from the views.py file.

Step11: Connect App URLs to Project URLs

Now you need to connect your app URLs to your project’s URL. I discussed earlier that in one Django project, there can be multiple applications. This step is to make your specific app accessible through your project.

Technically, by including your app’s URL in your project’s urls.py, you make sure that when someone visits your project, they can access the views you defined in your app.

To do this step, open the urls.py file from your project folder (django tutorial/first_django_project/first_django_project/urls.py) and include your app’s URLs. For simplicity, below is the complete code for urls.py of our project.

"""first_django_project URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path("", include('student_info.urls'))
]

Step11: Running the Development Server

So we are done with all our development. Now we need to run and test our Djnagon application. To run any web application we need a server right? Run below command to start a development server to test your Django application locally. You can view it in your web browser to make sure everything is working as expected.

python manage.py runserver
django-python-run-server

Once you run the above command you will get a local host server address like this: http://127.0.0.1:8000/. Open that localhost URL in your favorite browser and see the output.

final-django-application-project-made-by-python-tutorial

Final Thought

Django is a complex framework to work with backend and web application development with Python. I struggled a lot to learn the entire backbone of Django Framework.

My intention in writing this article is to explain you entire process of building a website or web application using Django so that you can get started with this framework quickly.

I think the best and easiest way to learn Django is to understand the concept and interrelation between Model, View, and Template. Once you learn how to connect these three modules of the Django framework then only you should move one to develop some projects, not before that.

This is the reason in this tutorial, I explained Model, View, and Template of Django with a very basic and simple application. I hope after reading this article you got some confidence about Django application. If you still have some doubts, let me know in the comment section below, and I will try my best to answer those.

Similar Read:

Leave a comment