DAY 1
What is Django and Its Advantages
1. What is Django?
Django is a high-level web framework written in Python. It helps
developers create websites and web applications quickly, securely, and
efficiently. Django follows the Model-View-Template (MVT) architecture,
which makes it easy to organize your code.
2. Purpose of Django
- To make web
development faster and easier
- To provide tools
for handling databases, URLs, templates, and web content
- To ensure security and maintainable code
for web applications
3. Advantages of Using Django
- Rapid
Development: Build
web applications quickly with built-in features like authentication and
admin panel
- Security: Protects
against common security threats like SQL injection and cross-site
scripting
- Scalability and
Maintainability: Its
modular structure allows your website to grow easily
- Free and
Open-Source: No
cost and has a large community support
4. Real-World Uses of Django
Django is used to build:
- Social
networking websites
- E-commerce
platforms
- Content
management systems (CMS)
- Dashboards and
analytics platforms
5. Why Django is Popular
- Easy to use for
Python developers
- Comes with
many built-in features
- Focuses on security
and efficiency
- Supported by
a large community with tutorials and documentation
6. Key Points to Remember
- Django helps
you create professional web applications quickly
- It is secure,
scalable, and maintainable
- Many popular
websites like Instagram and Pinterest use Django
Assignment for Students:
- Write a short
paragraph explaining why Django is popular for web development.
- Give one
real-world example of a website or application built with Django.
DAY 2
Installing Python, Django & Setting Up Virtual Environment
1. Installing Python
Python is the programming language used to develop Django applications. Before starting Django, you must install Python on your computer.
- Steps to install Python:
1. Download the latest version of Python from the official website: https://www.python.org/downloads/
2. Run the installer and select “Add Python to PATH” before clicking Install.
3. Verify installation by opening a terminal/command prompt and typing:
4. python --version
You should see the installed Python version.
2. Understanding Virtual Environments
A virtual environment is an isolated workspace that allows you to install Python packages for a specific project without affecting other projects on your computer.
- Benefits of using a virtual environment:
- Keeps project dependencies separate
- Avoids version conflicts between projects
- Makes it easier to manage and deploy Django applications
3. Creating a Virtual Environment
- Steps to create a virtual environment:
1. Open your terminal or command prompt
2. Navigate to your project folder
3. Run the command:
4. python -m venv myenv
(Here, myenv is the name of the virtual environment. You can choose any name.)
5. Activate the virtual environment:
§ Windows:
§ myenv\Scripts\activate
§ Mac/Linux:
§ source myenv/bin/activate
- Once activated, your terminal will show the virtual environment name at the beginning of the line, e.g., (myenv)
4. Installing Django in the Virtual Environment
- With the virtual environment activated, install Django using pip:
· pip install django
- Verify the installation by typing:
· python -m django --version
- If successful, the terminal will display the installed Django version.
5. Summary / Key Points
- Python must be installed before Django.
- A virtual environment isolates your project’s packages.
- Always activate the virtual environment before installing Django.
- Verify installation using python -m django --version.
Classwork:
- Install Python on your computer
- Create a virtual environment for your project
- Install Django in the virtual environment
Assignment:
- Take a screenshot of your virtual environment activated with Django installed
- Run python -m django --version and include the output in your submission
DAY 3;
HOW TO BUILD YOUR FIRST WEBPAGE USING DJANGO
We have 2 steps 1; creating of django project and 2- creating django app
HOW TO CREATE A DJANGO PROJECT
✅ STEP 1 — Install Python
Make sure Python is installed.
Open Command Prompt and type:
If it shows a version (e.g., Python 3.10), continue.
If not, download from python.org.
✅ STEP 2 — Create a Project Folder
Choose where you want your project.
Example:
✅ STEP 3 — Create a Virtual Environment
This helps keep your project clean.
Activate it:
Windows
❗ If you get “running scripts is disabled” error
Run this once:
Then activate again.
✅ STEP 4 — Install Django
✅ STEP 5 — Create Your First Django Project
Move inside the project:
Your folder will look like:
✅ STEP 6 — Start the Development Server
You will see something like:
Open your browser and go to:
You will see:
🎉 “The install worked successfully! Congratulations!”
This is your first Django welcome page.
OPTIONAL — Make Your Own Welcome Page
Step 7: Create an App in the django folder
Step 8: Add the App to Settings register the app in django project
Open:
Find INSTALLED_APPS and add:
Step 9: Create a View in Your App (what you want your app to show )
Open:
Add this:
Step 10: Add URL your app url link
Open:
Add:
😊 Final Result
Now run:
Visit:
You will see:
Welcome to my first Django project!
HOW TO NAVIGATE BACK TO MAIN FOLDER
On Windows (Command Prompt / PowerShell)
- To go up one folder:
cd ..
- To go up multiple levels, repeat .. with \:
cd ..\..
- To go directly to your home folder:
cd %HOMEPATH%
2️⃣ On Mac / Linux (Terminal)
- To go up one folder:
cd ..
- To go up multiple levels:
cd ../..
- To go directly to your home folder:
cd ~
3️⃣ Extra Useful Commands
Command | What it does |
pwd | Shows your current folder path |
ls / dir | Lists files and folders in current folder |
cd foldername | Enter a folder inside current folder |
✅ Tip:
If you’re inside your Django project and want to go back to the outer folder (where your virtual environment lives), just do:
cd ..
WORKING WITH TEMPLATE
Single-Page Django Website (Home Page)
STEP 1 — Create Django Project
Open your terminal:
django-admin startproject singlepage
cd singlepage
Structure:
singlepage/
├── manage.py
└── singlepage/
├── __init__.py
├── settings.py
├── urls.py
├── wsgi.py
└── asgi.py
STEP 2 — Create an App
python manage.py startapp pages
Structure now:
singlepage/
└── pages/
├── __init__.py
├── admin.py
├── apps.py
├── models.py
├── tests.py
└── views.py
STEP 3 — Add App to Settings
Open singlepage/settings.py → INSTALLED_APPS:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'pages', # Add your app here
]
STEP 4 — Create a View
Open pages/views.py and add:
from django.shortcuts import render
def home(request):
return render(request, 'home.html')
STEP 5 — Create Template Folder
Inside your app pages/, create:
pages/templates/
Create home.html:
<!DOCTYPE html>
<html>
<head>
<title>Home Page</title>
</head>
<body>
<h1>Welcome to My Single-Page Django Website</h1>
<p>This is a simple page created with Django.</p>
</body>
</html>
Folder structure now:
singlepage/
└── pages/
└── templates/
└── home.html
STEP 6 — Add URL
Open singlepage/urls.py and update:
from django.contrib import admin
from django.urls import path
from pages.views import home
urlpatterns = [
path('admin/', admin.site.urls),
path('', home), # Home page
]
STEP 7 — Run the Server
python manage.py runserver
Open your browser:
http://127.0.0.1:8000/
You should see:
“Welcome to My Single-Page Django Website”
✅ Final Folder Structure for Single Page
singlepage/
├── manage.py
├── singlepage/
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ ├── wsgi.py
│ └── asgi.py
└── pages/
├── __init__.py
├── admin.py
├── apps.py
├── models.py
├── tests.py
├── views.py
└── templates/
└── home.html
CREATE A SMALL WEBSITE WITH 3 PAGES USING DJANGO.
STEP 1 — Create Django Project
In your terminal:
✅ STEP 2 — Create an App For the Pages
✅ STEP 3 — Add App to Settings
Open:
Find INSTALLED_APPS and add:
✅ STEP 4 — Create 3 Views (Home, About, Contact)
Open:
Replace everything with:
✅ STEP 5 — Create Templates Folder
Inside your project, create:
Inside this folder, create:
📄 home.html
📄 about.html
📄 contact.html
✅ STEP 6 — Add URLs
Open:
Replace it with:
✅ STEP 7 — Run Server
Now open your browser:
Home → http://127.0.0.1:8000
About → http://127.0.0.1:8000/about/
Contact → http://127.0.0.1:8000/contact/
🎉 You now have a small Django website with 3 pages!
WEEK 2;
working with static folder
Python 3.12.3 + Django 4.2.x
Installation Recommendation
1. Activate your virtual environment (always use venv for projects):
python -m venv myenvmyenv\Scripts\activate2. Install Django 4.2.x explicitly:
pip install django==4.23. Verify versions:
python --version# Should show: Python 3.12.3 python -m django --version# Should show: 4.2.x STEP-BY-STEP: 1-Page Styled Django Project
STEP 1 — Install Python 3.12.3
- Go to the official Python website:
https://www.python.org/downloads/release/python-3123/ - Download Windows Installer (64-bit).
- During installation:
- ✅ Check Add Python to PATH
- ✅ Check Install launcher for all users
- Proceed with default settings
- Verify installation in PowerShell or CMD:
python --version
Expected output:
Python 3.12.3
STEP 2 — Create Project Folder
Create a folder for your project:
mkdir C:\Users\Zbook\Desktop\styledsite
cd C:\Users\Zbook\Desktop\styledsite
STEP 3 — Create Virtual Environment (Recommended)
python -m venv myenv
Activate it:
myenv\Scripts\activate
You should see (myenv) in your terminal prompt.
STEP 4 — Install Django 4.2.x
Inside the virtual environment, run:
pip install django==4.2
Check Django version:
python -m django --version
Expected output:
4.2.x
STEP 5 — Start Django Project
django-admin startproject styledsite .
Folder structure:
styledsite/
├── manage.py
└── styledsite/
├── __init__.py
├── settings.py
├── urls.py
├── wsgi.py
└── asgi.py
STEP 6 — Create Django App
python manage.py startapp pages
Folder structure:
pages/
├── __init__.py
├── admin.py
├── apps.py
├── models.py
├── tests.py
└── views.py
STEP 7 — Add App to Settings
Open styledsite/settings.py → INSTALLED_APPS:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'pages', # <-- add your app here
]
STEP 8 — Create View
Open pages/views.py and add:
from django.shortcuts import render
def home(request):
return render(request, 'pages/home.html')
STEP 9 — Create Template Folder and HTML
Inside pages/, create:
pages/templates/pages/
Create home.html:
<!DOCTYPE html>
<html>
<head>
<title>Home Page</title>
{% load static %}
<link rel="stylesheet" href="{% static 'pages/style.css' %}">
</head>
<body>
<header>
<h1>Welcome to My Styled Django Page</h1>
</header>
<main>
<p>This is a fully styled page using CSS!</p>
<button>Click Me</button>
</main>
<footer>
<p>© 2025 My Django Website</p>
</footer>
</body>
</html>
Folder structure:
pages/
└── templates/
└── pages/
└── home.html
STEP 10 — Add CSS
Inside pages/, create:
pages/static/pages/
Create style.css:
body {
font-family: Arial, sans-serif;
background-color: #f0f8ff;
margin: 0;
padding: 0;
}
header {
background-color: #4CAF50;
color: white;
text-align: center;
padding: 30px;
}
main {
text-align: center;
margin-top: 50px;
}
button {
padding: 10px 20px;
background-color: #4CAF50;
border: none;
color: white;
font-size: 16px;
cursor: pointer;
border-radius: 5px;
}
button:hover {
background-color: #45a049;
}
footer {
text-align: center;
background-color: #222;
color: white;
padding: 15px;
position: fixed;
bottom: 0;
width: 100%;
}
Folder structure:
pages/
└── static/
└── pages/
└── style.css
STEP 11 — Add URL
Open styledsite/urls.py:
from django.contrib import admin
from django.urls import path
from pages.views import home
urlpatterns = [
path('admin/', admin.site.urls),
path('', home),
]
STEP 12 — Apply Migrations
python manage.py migrate
STEP 13 — Run Server
python manage.py runserver
Open browser:
http://127.0.0.1:8000/
You will see a fully styled page with header, main content, button, and footer.
✅ Full Folder Structure
styledsite/
├── manage.py
├── styledsite/
│ ├── __init__.py
│ ├── settings.py
│ ├── urls.py
│ ├── wsgi.py
│ └── asgi.py
└── pages/
├── __init__.py
├── admin.py
├── apps.py
├── models.py
├── tests.py
├── views.py
├── templates/
│ └── pages/
│ └── home.html
└── static/
└── pages/
└── style.css
MODEL
A model means creating a Table to store a record or data like Name, Age
STEPS USED TO CREATE A MODEL
STEP 1: Decide what you want to store
We want to store:
-
Student full name
-
Student course
STEP 2: Open models.py
In your app folder:
class Student(models.Model):
fullname = models.CharField(max_length=100)
course = models.CharField(max_length=100)
def __str__(self):
return self.fullnameVIEW Function in DjangoHow to createhomefunction in view
The home view displays the Home Page of your website.def home(request):
return render(request, 'pages/home.html')
# 'render' is a Django function that displays an HTML page
# 'request' contains all the information from the browser
# 'pages/home.html' is the path to the HTML template we want to show
# 'return' sends the rendered HTML back to the browserCREATING A VIEW FOR REGISTER def register(request):
# Check if the form was submitted
if request.method == 'POST':
# Get the value entered in the "fullname" input field of the form
name = request.POST.get('fullname')
# Get the value entered in the "course" input field of the form
course = request.POST.get('course')
# Create a new student record in the database using the data from the form
Student.objects.create(
fullname=name, # Set the fullname column
course=course # Set the course column
)
# After saving, redirect the user to the students list page
return redirect('/students/')
# If the form was not submitted, just show the registration page
return render(request, 'pages/register.html')
FUNCTION TO VIEW STUDENT RECORD def students(request): # Get all student records from the database students = Student.objects.all()
# Render the 'students.html' template and send the list of students to it # The template can use 'students' variable to display all registered students return render(request, 'pages/students.html', {'students': students})
CREAYING A VIEW FOR REGISTER AND VIEW COMPLETE CODE
def register(request):
if request.method == 'POST':
name = request.POST.get('fullname')
course = request.POST.get('course')
Student.objects.create(
fullname=name,
course=course
)
return redirect('/students/')
return render(request, 'pages/register.html')
def students(request):
students = Student.objects.all()
return render(request, 'pages/students.html', {'students': students})CREATING OF URL
# Import Django's admin module to use the built-in admin site
from django.contrib import admin
# Import 'path' function to map URLs to views
from django.urls import path
# Import the view functions from our pages app
from pages.views import home, register, students
# Define URL patterns: tells Django which view to run for each URL
urlpatterns = [
# URL for Django admin site: /admin/
path('admin/', admin.site.urls),
# URL for home page: /
path('', home),
# URL for register page: /register/
path('register/', register),
# URL for students list page: /students/
path('students/', students),
]
Create Register Page (HTML Form)
<!-- Heading for the registration page -->
<h2>Student Registration</h2>
<!-- Start of the registration form -->
<!-- method="POST" means the form will send data to the server -->
<form method="POST">
<!-- CSRF token: security feature in Django to prevent cross-site attacks -->
{% csrf_token %}
<!-- Label and input for student's full name -->
<label>Full Name:</label><br>
<!-- 'name' attribute must match what the view expects (request.POST.get('fullname')) -->
<input type="text" name="fullname" required><br><br>
<!-- Label and input for student's course -->
<label>Course:</label><br>
<!-- 'name' attribute must match what the view expects (request.POST.get('course')) -->
<input type="text" name="course" required><br><br>
<!-- Submit button to send the form data -->
<button type="submit">Register</button>
</form>
<br>
<!-- Link to go back to the home page -->
<a href="/">Back Home</a>Topic: Django Template Language Basics
(Where {{ variable }}, {% for %}, and {% csrf_token %} come from)
Introduction
Django uses Python to handle data (in views and models) and HTML to display content.
Sometimes, we need to show Python data dynamically inside HTML.
This is where Django Template Language (DTL) comes in.
It allows HTML files to use Python-like syntax to display data, loop through lists, and secure forms.
Sub-Topic 1: {{ variable }}
What it is: A placeholder to show data from Python in HTML.
Where it comes from: Passed from the view using render(request, template, context).
How to write:
Example:
Displays the fullname of a student from the database.
Sub-Topic 2: {% for ... in ... %}
What it is: A loop to repeat HTML for every item in a list or queryset.
Where it comes from: A Python list or Django model queryset passed from the view.
How to write:
Example:
Optional: {% empty %} shows a message if the list is empty.
Sub-Topic 3: {% csrf_token %}
What it is: A security token used in POST forms to prevent malicious attacks (Cross-Site Request Forgery).
Where it comes from: Django automatically generates it for every session.
How to write:
Example:
Always include {% csrf_token %} in every POST form.
Summary Table
DTL Tag Purpose Example {{ variable }}Show Python data in HTML {{ student.fullname }}{% for item in list %}Loop through a list or queryset {% for student in students %} ... {% endfor %}{% csrf_token %}Secure forms from attacks Place inside <form method="POST">
Create VIEW Page (HTML Form)
<!-- Heading for the page -->
<h2>Registered Students</h2>
<!-- Start an unordered list to show all students -->
<ul>
<!-- Loop through each student in the 'students' variable passed from the view -->
{% for student in students %}
<!-- Display each student's fullname and course in a list item -->
<li>{{ student.fullname }} — {{ student.course }}</li>
{% empty %}
<!-- This shows if there are no students in the list -->
<li>No student registered yet</li>
{% endfor %}
</ul>
<br>
<!-- Link to go back to the home page -->
<a href="/">Back Home</a>
CREATING OF REGISTER FORM
➕ STEP 20 — Add Links on Home Page (SIMPLE METHOD)
Edit home.html
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title></head><body> <p>This is a fully styled page using CSS!</p>
<a href="/register/">Register Student</a> <br><br>
<a href="/students/">View Students</a>
</body></html>✅ This uses the same method as:
<a href="/about/">About</a>Create file:
📄 pages/templates/register.html
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title></head><body> <!DOCTYPE html><html><head> <title>Student Register</title></head><body>
<h2>Student Registration</h2>
<form method="POST"> {% csrf_token %}
<label>Full Name:</label><br> <input type="text" name="fullname" required><br><br>
<label>Course:</label><br> <input type="text" name="course" required><br><br>
<button type="submit">Register</button></form>
<br><a href="/">Back Home</a>
</body></html></body></html>
</html>
➕ STEP 14 — Create Student Model (Register Data)
Open pages/models.py
from django.db import models
# Create your models here.
class Student(models.Model): fullname = models.CharField(max_length=100) course = models.CharField(max_length=100)
def __str__(self): return self.fullname➕ STEP 15 — Make & Apply Migrations
Run in terminal:
python manage.py makemigrations
python manage.py migrate➕ STEP 16 — Create Register & View Pages (Views)
Open pages/views.py
(keep your home view, ADD these)
# Register studentdef register(request): if request.method == 'POST': fullname = request.POST.get('fullname') course = request.POST.get('course')
# Save the data to the Student model Student.objects.create(fullname=fullname, course=course)
# Redirect to students list page return redirect('students')
# If GET request, just show the form return render(request, 'register.html')
# Show all studentsdef students(request): students = Student.objects.all() return render(request, 'students.html', {'students': students})👉 No forms.py used (very simple for beginners)
➕ STEP 17 — Add URLs (Simple Method)
Open styledsite/urls.py
from django.contrib import adminfrom django.urls import pathfrom pages.views import about, home,register, students
urlpatterns = [ path('admin/', admin.site.urls), path('', home), # home page path('about/', about), # about page path('register/', register), # about page path('students/', students, name='students'), # ✅ MUST have name='students'
]
➕ STEP 19 — Create Students List Page (View Only)
Create file:
📄 pages/templates/students.html
<!DOCTYPE html><html><head> <title>Students List</title></head><body>
<h2>Registered Students</h2>
<ul> {% for student in students %} <li>{{ student.fullname }} — {{ student.course }}</li> {% empty %} <li>No student registered yet</li> {% endfor %}</ul>
<br><a href="/">Back Home</a>
</body></html>
➕ STEP 21 — Restart Server
python manage.py runserver
How to create full crudHome Page; HOME.HTML
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title></head><body> <p>This is a fully styled page using CSS!</p>
<a href="/register/">Register Student</a> <br><br>
<a href="/students/">View Students</a>
</body></html><a href="/register/">Register Student</a><a href="{% url 'register' %}">Register Student</a>

