Week 1: Day 1: Installation and Python Basics: What is Python?
-
Python is a programming language used to write instructions for computers.
-
It is easy to learn, readable, and popular for beginners and experts.
-
You can use Python to make websites, apps, games, and more.
2. Why Use Python?
-
Easy to Learn: Simple and clear syntax.
-
Versatile: Can be used for web development, data analysis, AI, automation.
-
Readable: Code is clean and easy to understand.
-
Community Support: Lots of tutorials, libraries, and help online.
-
Fast Development: Can create programs quickly.
3. Where is Python Used?
-
Web Development: Using frameworks like Django or Flask.
-
Data Science & AI: For analyzing data and building models.
-
Automation: Automating repetitive tasks.
-
Game Development: Simple games and simulations.
-
Education: Teaching programming to beginners.
Day 2: Python Syntax
Perfect, Raheem! Let’s continue.
Python Basics: Syntax and Printing
1. What is Python Syntax?
-
Python syntax is the set of rules you follow when writing Python code.
-
It tells Python how to understand your instructions.
Example:
x = 10 if x > 5: print("x is greater than 5")
2. Why Use Python Syntax?
-
Without correct syntax, Python cannot run your code.
-
Helps your code stay organized and readable.
3. Where is Python Syntax Used?
-
Everywhere in Python:
-
Writing variables
-
Creating loops
-
Writing functions
-
Building classes
-
Making Django apps
-
4. What is Printing?
-
Printing is showing output on the screen using
print().
Example:
print("Hello, Students!")
5. Why Use Printing?
-
To show results to the user.
-
To check values and debug your code.
-
To learn programming by seeing output.
6. Where is Printing Used?
-
Displaying messages, results, or variables.
-
Showing output from loops, functions, or Django views.
Example:
name = "Ali" age = 12 print(f"My name is {name} and I am {age} years old-
Class 3: Basic Input
Explanation:
-
Use
input()to get information from the user.
Example:
name = input("Enter your name: ")
print("Hello, " + name + "!")
Classwork:
-
Ask the user for their favorite color and print it.
Assignment:
-
Ask the user for their age and print a message:
"You are 12 years old"
Class 4: Practice
-
Combine printing and input.
Example:
name = input("Enter your name: ")
age = input("Enter your age: ")
print("Hello, " + name + ". You are " + age + " years old.")
Classwork:
-
Ask the user for their favorite food and drink, then print a sentence:
"I like pizza and orange juice"
Assignment:
-
Create a mini program asking for 3 pieces of information about a student (name, age, class) and print them nicely.
✅ Outcome Week 1:
-
Students know how to write Python code, use print statements, get input, and add comments.
-
Ready to move on to Week 2: Variables and Data Types.
Week 2: Variables and Data Types
Objective: Learn how to store and use data in Python — important for Django models and views.
Class 1: What is a Variable?
Explanation:
-
A variable is a name that stores data.
-
You can use it to store numbers, text, or other information.
Example:
name = "Ali"
age = 12
print(name)
print(age)
Classwork:
-
Create variables for your name, age, and favorite color, then print them.
Assignment:
-
Create variables for 3 students: name, age, and class. Print their details.
Class 2: Data Types
Explanation:
-
Python has different types of data:
-
int → whole numbers
-
float → decimal numbers
-
str → text
-
bool → True or False
Example:
age = 12 # int
price = 9.99 # float
name = "Ali" # str
is_student = True # bool
Classwork:
-
Create one variable of each type and print them with labels.
Assignment:
-
Create variables for a book: title (str), pages (int), price (float), available (bool). Print them.
Class 3: Changing Variables
Explanation:
-
Variables can change values anytime.
Example:
age = 12
print(age)
age = 13
print(age)
Classwork:
-
Change your favorite color variable and print it before and after.
Assignment:
-
Create a student’s age variable, increase it by 1, and print:
"Next year, Ali will be 13 years old"
Class 4: Type Conversion
Explanation:
-
Sometimes you need to change data type using
int(),float(), orstr().
Example:
age = input("Enter your age: ") # input gives string
age = int(age) # convert to number
print(age + 1)
Classwork:
-
Ask the user for a number and print double the value.
Assignment:
-
Ask for price of an item as input and add 100 to it, then print the total.
Class 5: Practice Mini Project
Task: Student Info Program
-
Ask the user for name, age, and class
-
Store them in variables
-
Print a message like:
"Ali is 212 years old in class 6"
Example:
name = input("Enter your name: ")
age = int(input("Enter your age: "))
class_no = input("Enter your class: ")
print(name + " is " + str(age) + " years old in class " + class_no)
Outcome:
-
Students understand variables, data types, type conversion, and storing info.
Great, Raheem! Let’s move on to Week 3: Operators and Expressions.
Week 3: Operators and Expressions
Objective: Learn how to perform calculations and comparisons in Python — important for logic in Django views and templates.
Class 1: Arithmetic Operators
Explanation:
-
Used to do math in Python.
-
Common operators:
-
+→ add -
-→ subtract -
*→ multiply -
/→ divide -
%→ remainder
-
Example:
a = 10
b = 3
print(a + b) # 13
print(a - b) # 7
print(a * b) # 30
print(a / b) # 3.3333
print(a % b) # 1
Classwork:
-
Create two numbers and print their sum, difference, product, division, and remainder.
Assignment:
-
Ask the user for two numbers and print all arithmetic results.
Class 2: Comparison Operators
Explanation:
-
Used to compare values. Result is True or False.
-
Operators:
==,!=,>,<,>=,<=
Example:
x = 5
y = 3
print(x == y) # False
print(x > y) # True
print(x != y) # True
Classwork:
-
Compare two numbers and print which one is bigger.
Assignment:
-
Ask the user for age and check if they are old enough to enter a class (e.g., 12+).
Class 3: Logical Operators
Explanation:
-
Combine conditions using
and,or,not.
Example:
age = 15
has_ticket = True
can_enter = age >= 12 and has_ticket
print(can_enter) # True
Classwork:
-
Check if a number is positive and even.
Assignment:
-
Ask user for age and permission, then check if they can access a page.
Class 4: Assignment Operators
Explanation:
-
Assign or update values with operators like
=,+=,-=,*=
Example:
x = 5
x += 3 # x = x + 3
print(x) # 8
Classwork:
-
Start with a number 10, subtract 4, multiply by 2, divide by 3 using assignment operators.
Assignment:
-
Create a variable
points = 50. Add 10, subtract 5, multiply by 2, then divide by 5. Print result.
Class 5: Expressions
Explanation:
-
Expressions are combinations of variables, operators, and values that produce a result.
Example:
a = 5
b = 3
c = (a + b) * 2
print(c) # 16
Classwork:
-
Create an expression for
((10 + 5) * 2) / 3and print the result.
Assignment:
-
Ask user for length and width of a rectangle, calculate area and perimeter using expressions, and print them.
Class 6: Mini Project
Task: Simple Calculator Program
-
Ask user for two numbers
-
Ask for operation: add, subtract, multiply, divide
-
Print result based on operation
Example:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
op = input("Enter operation (+,-,*,/): ")
if op == "+":
print(num1 + num2)
elif op == "-":
print(num1 - num2)
elif op == "*":
print(num1 * num2)
elif op == "/":
print(num1 / num2)
else:
print("Invalid operation")
Outcome:
-
Students understand arithmetic, comparison, logical, and assignment operators.
-
Ready to move on to Week 4: Conditional Statements (If-Else).
Perfect, Raheem! Let’s continue with Week 4: Conditional Statements (If-Else).
Week 4: Conditional Statements (If-Else)
Objective: Learn how to make decisions in Python — very important for Django views.
Class 1: If Statement
Explanation:
-
ifchecks a condition. If it’s True, code inside runs.
Example:
age = 15
if age >= 12:
print("You can enter the class")
Classwork:
-
Check if a number is positive. Print
"Positive number"if true.
Assignment:
-
Ask user for age and print
"Adult"if age >= 18.
Class 2: If-Else Statement
Explanation:
-
elseruns if theifcondition is False.
Example:
age = 10
if age >= 12:
print("You can enter")
else:
print("Too young to enter")
Classwork:
-
Ask user for a number. Print
"Even"if divisible by 2, else"Odd".
Assignment:
-
Check if user’s age is enough for school (6+). Print appropriate message.
Class 3: Elif (Else-If) Statement
Explanation:
-
elifchecks another condition if the first is False.
Example:
marks = 75
if marks >= 90:
print("Grade A")
elif marks >= 70:
print("Grade B")
else:
print("Grade C")
Classwork:
-
Ask user for marks (0–100) and print grade:
-
= 90 → A
-
70–89 → B
-
50–69 → C
-
<50 → F
-
Assignment:
-
Ask user for temperature and print:
-
30 → "Hot"
-
20–30 → "Warm"
-
<20 → "Cold"
-
Class 4: Nested If Statements
Explanation:
-
Put one
ifinside another to check multiple conditions.
Example:
age = 16
has_permission = True
if age >= 12:
if has_permission:
print("You can enter")
else:
print("You need permission")
else:
print("Too young")
Classwork:
-
Check if a number is positive and even. Print
"Positive even"or"Other".
Assignment:
-
Ask for age and grade.
-
If age >= 12 and grade >= 50 →
"Pass" -
Else →
"Fail"
Class 5: Mini Project
Task: School Admission Checker
-
Ask user for:
-
Age
-
Grade
-
Permission (Yes/No)
-
-
Print if they can join class or cannot join.
Example:
age = int(input("Enter your age: "))
grade = int(input("Enter your grade: "))
permission = input("Do you have permission (Yes/No)? ")
if age >= 12:
if grade >= 50:
if permission.lower() == "yes":
print("You can join the class")
else:
print("Permission required")
else:
print("Grade too low")
else:
print("Too young for this class")
Outcome:
-
Students understand decision making, which is needed to control Django views and form logic.
Perfect, Raheem! Let’s move on to Week 5: Loops.
Week 5: Loops
Objective: Learn how to repeat tasks in Python — very useful for Django views and templates.
Class 1: For Loop
Explanation:
-
forloop repeats code for each item in a list, range, or other collection.
Example 1 (list):
students = ["Ali", "Aisha", "Emmanuel"]
for student in students:
print(student)
Example 2 (range):
for i in range(5):
print(i) # prints 0,1,2,3,4
Classwork:
-
Create a list of 5 fruits and print each fruit using a for loop.
Assignment:
-
Print numbers from 1 to 10 using a for loop.
Class 2: While Loop
Explanation:
-
whileloop repeats code as long as a condition is True.
Example:
i = 1
while i <= 5:
print(i)
i += 1 # increase i by 1 each time
Classwork:
-
Print numbers from 10 down to 1 using a while loop.
Assignment:
-
Ask the user to enter a number. Print all numbers from 1 to that number using a while loop.
Class 3: Break and Continue
Explanation:
-
break→ stops the loop completely -
continue→ skips the current step and goes to next iteration
Example (break):
for i in range(10):
if i == 5:
break
print(i)
Example (continue):
for i in range(5):
if i == 2:
continue
print(i)
Classwork:
-
Loop numbers 1–10, stop when number is 7.
Assignment:
-
Loop numbers 1–5, skip number 3 using continue.
Class 4: Nested Loops
Explanation:
-
A loop inside another loop. Useful for tables or grids.
Example:
for i in range(1,4):
for j in range(1,4):
print(i, j)
Classwork:
-
Print a 3x3 multiplication table.
Assignment:
-
Create a loop that prints a pattern:
*
**
***
****
Class 5: Mini Project
Task: Student List Display
-
Create a list of 5 students (dictionaries with name and age)
-
Use a loop to print:
"Ali is 12 years old"
Example:
students = [
{"name": "Ali", "age": 12},
{"name": "Aisha", "age": 13},
{"name": "Emmanuel", "age": 14}
]
for s in students:
print(f"{s['name']} is {s['age']} years old")
Outcome:
-
Students understand repetition and loops, which is needed for displaying multiple items in Django templates.
Intermediate
Python Training – Week 3: Functions
Day 1 (Mon) – Introduction to Functions
1. What is it?
A function is a block of code that does a task. Instead of repeating code, we write it once and call it anytime.
2. Code Example
def say_hello():
print("Hello, welcome to Python!")
# Call the function
say_hello()
Explanation:
- def → used to define a function.
- say_hello() → calling the function runs the code.
✅ Class Work
Write a function that prints "Good Morning".
π Assignment
Write a function called greet() that prints "Hello, Student!".
Day 2 (Tue) – Functions with Parameters
1. What is it?
We can give functions inputs (parameters).
2. Code Example
def greet(name):
print("Hello, " + name)
greet("Raheem")
greet("Mary")
Explanation:
- name is a parameter.
- When calling the function, we give a value like "Raheem".
✅ Class Work
Write a function square(num) that prints the square of a number.
π Assignment
Write a function add(a, b) that prints the sum of two numbers.
Day 3 (Wed) – Functions with Return Values
1. What is it?
Functions can return values to be used later.
2. Code Example
def add(a, b):
return a + b
result = add(5, 3)
print("The sum is:", result)
Explanation:
- return sends the answer back.
- We can save it in a variable like result.
✅ Class Work
Write a function multiply(a, b) that returns the product.
π Assignment
Write a function is_even(num) that returns True if number is even, else False.
Day 4 (Thu) – Real Life Example with Functions
Example: Student Grading Function
def grade_student(score):
if score >= 70:
return "A"
elif score >= 50:
return "C"
else:
return "Fail"
print("Student 1:", grade_student(75))
print("Student 2:", grade_student(40))
Explanation:
- Function checks the score.
- Returns "A", "C", or "Fail".
- Very useful in schools or exams!
✅ Class Work
Write a function check_age(age) that returns "Adult" if age ≥ 18, else "Minor".
π Assignment
Write a function check_login(username, password) → if username = "admin" and password = "1234", return "Access Granted", else "Access Denied".
Day 5 (Fri) – Assessment
Practical Test (10 marks)
- Write a function say_hi() that prints "Hi". (2 marks)
- Write a function double(num) that returns double of the number. (2 marks)
- Write a function subtract(a, b) that returns the difference. (2 marks)
- Write a function check_number(num) that returns "Even" if even, else "Odd". (2 marks)
- Write a function grade(score) that returns "Pass" if score ≥ 50, else "Fail". (2 marks)
✅ Step-by-Step Solutions
Q1 Solution
def say_hi():
print("Hi")
say_hi()
Q2 Solution
def double(num):
return num * 2
print(double(5)) # Output: 10
Q3 Solution
def subtract(a, b):
return a - b
print(subtract(10, 4)) # Output: 6
Q4 Solution
def check_number(num):
if num % 2 == 0:
return "Even"
else:
return "Odd"
print(check_number(7)) # Output: Odd
Q5 Solution
def grade(score):
if score >= 50:
return "Pass"
else:
return "Fail"
print(grade(65)) # Output: Pass
print(f"{s['name']} is {s['age']} years old")
Classwork:
Create a list of 3 books, each book is a dictionary with title and author. Print all books.
Assignment:
Create a list of 3 teachers, each with name and subject. Print: "Teacher Ali teaches Math" format.
print(f"{s['name']} is {s['age']} years old")
Classwork:
Create a list of 3 books, each book is a dictionary with
titleandauthor. Print all books.
Assignment:
Create a list of 3 teachers, each with
nameandsubject. Print:"Teacher Ali teaches Math"format.
π§ Python Data Structures
A data structure is a way to store and organize data so your program can use it easily and efficiently.
Data Structure
Symbol
Example
List
[ ]
fruits = ["Apple", "Banana"]
Tuple
( )
colors = ("Red", "Green")
Set
{ }
numbers = {1, 2, 3}
Dictionary
{ } (key:value)
student = {"name":"Amina", "age":12}
Python has 4 main built-in data structures:
-
List
-
Tuple
-
Set
-
Dictionary
A data structure is a way to store and organize data so your program can use it easily and efficiently.
| Data Structure | Symbol | Example |
|---|---|---|
| List | [ ] |
fruits = ["Apple", "Banana"] |
| Tuple | ( ) |
colors = ("Red", "Green") |
| Set | { } |
numbers = {1, 2, 3} |
| Dictionary | { } (key:value) |
student = {"name":"Amina", "age":12} |
Python has 4 main built-in data structures:
-
List
-
Tuple
-
Set
-
Dictionary
1️⃣ List
Meaning:
A list is like a row of boxes where you can store many items, change them, or add more items.
Example:
students = ["Amina", "John", "Mary"]
print(students[0]) # Amina
students.append("Tunde") # Add new student
print(students)
List function
Function
What It Does
Example
len()
Count items
len(fruits)
append()
Add at end
fruits.append("Mango")
insert()
Add at index
fruits.insert(1,"Mango")
remove()
Remove by value
fruits.remove("Banana")
pop()
Remove by index
fruits.pop(1)
index()
Find position
fruits.index("Apple")
count()
Count duplicates
fruits.count("Apple")
sort()
Arrange items
fruits.sort()
reverse()
Reverse order
fruits.reverse()
copy()
Copy list
fruits.copy()
clear()
Remove all items
fruits.clear()
Mini Exercise:
-
Create a list of 5 fruits and print each fruit in uppercase.
# Create a list of 5 fruits
fruits = ["apple", "banana", "mango", "orange", "pineapple"]
# Print each fruit in uppercase
for fruit in fruits:
print(fruit.upper())
Output:
APPLE
BANANA
MANGO
ORANGE
PINEAPPLE
This code uses a for loop to go through each fruit and the upper() method to convert it to upper case
Key Points:
-
Ordered (items have position)
-
Changeable (you can add, remove, or edit items)
-
Allows duplicates
Meaning:
A list is like a row of boxes where you can store many items, change them, or add more items.
Example:
students = ["Amina", "John", "Mary"]
print(students[0]) # Amina
students.append("Tunde") # Add new student
print(students)
List function
Function
What It Does
Example
len()
Count items
len(fruits)
append()
Add at end
fruits.append("Mango")
insert()
Add at index
fruits.insert(1,"Mango")
remove()
Remove by value
fruits.remove("Banana")
pop()
Remove by index
fruits.pop(1)
index()
Find position
fruits.index("Apple")
count()
Count duplicates
fruits.count("Apple")
sort()
Arrange items
fruits.sort()
reverse()
Reverse order
fruits.reverse()
copy()
Copy list
fruits.copy()
clear()
Remove all items
fruits.clear()
Mini Exercise:
-
Create a list of 5 fruits and print each fruit in uppercase.
# Create a list of 5 fruits
fruits = ["apple", "banana", "mango", "orange", "pineapple"]
# Print each fruit in uppercase
for fruit in fruits:
print(fruit.upper())
Output:
APPLE
BANANA
MANGO
ORANGE
PINEAPPLE
This code uses a for loop to go through each fruit and the upper() method to convert it to upper case
Key Points:
-
Ordered (items have position)
-
Changeable (you can add, remove, or edit items)
-
Allows duplicates
2️⃣ Tuple
Meaning:
A tuple is like a list but cannot be changed after creation.
Example:
colors = ("red", "green", "blue")
print(colors[1]) # green
Mini Exercise:
-
Make a tuple of 5 Nigerian states and print all of them.
Key Points:
-
Ordered
-
Cannot be changed (immutable)
-
Allows duplicates
Meaning:
A tuple is like a list but cannot be changed after creation.
Example:
colors = ("red", "green", "blue")
print(colors[1]) # green
Mini Exercise:
-
Make a tuple of 5 Nigerian states and print all of them.
Key Points:
-
Ordered
-
Cannot be changed (immutable)
-
Allows duplicates
3️⃣ Set
Meaning:
A set is a collection of unique items, meaning no duplicates.
Example:
numbers = {1, 2, 3, 3, 4}
print(numbers) # {1, 2, 3, 4}
Mini Exercise:
-
Create a set of 5 numbers and add one more number.
Key Points:
-
Unordered (no position)
-
Unique items only
-
Changeable (can add/remove items)
Meaning:
A set is a collection of unique items, meaning no duplicates.
Example:
numbers = {1, 2, 3, 3, 4}
print(numbers) # {1, 2, 3, 4}
Mini Exercise:
-
Create a set of 5 numbers and add one more number.
Key Points:
-
Unordered (no position)
-
Unique items only
-
Changeable (can add/remove items)
4️⃣ Dictionary
Meaning:
A dictionary stores data in key-value pairs.
-
Like your phone contacts: Name → Phone Number
Example:
student = {"name": "Amina", "age": 12, "class": "Primary 5"}
print(student["name"]) # Amina
student["age"] = 13 # Update age
Mini Exercise:
-
Make a dictionary for 3 students with their age and class.
Key Points:
-
Unordered (no position)
-
Changeable
-
Access items using keys
Data Structure
Common Functions
What It Does
Tuple
len(), count(), index()
Count items, find duplicates, get position
Set
add(), remove(), discard(), pop(), clear(), union(), intersection()
Add/remove items, combine sets, find common/unique
Dictionary
keys(), values(), items(), get(), update(), pop(), clear()
Work with key-value pairs: access, update, remove
Meaning:
A dictionary stores data in key-value pairs.
-
Like your phone contacts: Name → Phone Number
Example:
student = {"name": "Amina", "age": 12, "class": "Primary 5"}
print(student["name"]) # Amina
student["age"] = 13 # Update age
Mini Exercise:
-
Make a dictionary for 3 students with their age and class.
Key Points:
-
Unordered (no position)
-
Changeable
-
Access items using keys
| Data Structure | Common Functions | What It Does |
|---|---|---|
| Tuple | len(), count(), index() |
Count items, find duplicates, get position |
| Set | add(), remove(), discard(), pop(), clear(), union(), intersection() |
Add/remove items, combine sets, find common/unique |
| Dictionary | keys(), values(), items(), get(), update(), pop(), clear() |
Work with key-value pairs: access, update, remove |
✅ Quick Comparison Table
Data Structure
Ordered
Changeable
Allows Duplicates
Example
List
Yes
Yes
Yes
["Amina", "John"]
Tuple
Yes
No
Yes
("red", "blue")
Set
No
Yes
No
{1, 2, 3}
Dictionary
No
Yes
Keys must be unique
{"name":"Amina"}
| Data Structure | Ordered | Changeable | Allows Duplicates | Example |
|---|---|---|---|---|
| List | Yes | Yes | Yes | ["Amina", "John"] |
| Tuple | Yes | No | Yes | ("red", "blue") |
| Set | No | Yes | No | {1, 2, 3} |
| Dictionary | No | Yes | Keys must be unique | {"name":"Amina"} |
Week 2: Classes and Objects
Good question π
We need to learn “class” in Python because classes are the foundation of Object-Oriented Programming (OOP) — one of the most powerful ways to write clean, reusable, and organized code.
Let’s break it down in simple Nigerian English π
π§ 1. What is a Class?
A class is like a blueprint or plan for creating something.
For example:
Think of a "class" as a plan for building cars.
-
The class will describe what every car should have (like colour, engine, tyre size).
-
When you use the plan to make a real car, that real car is called an object.
So a class is just a design, while an object is the actual thing made from that design.
π‘ 2. Why Do We Need to Learn Class?
(a) To Organize Code
When your project grows big, classes help you group related functions and data together.
Example: you can have a class for Students, another for Teachers, and another for Subjects.
(b) To Reuse Code Easily
Once you create a class, you can use it many times to make new objects without writing the same code again.
Example: one Student class can create hundreds of student objects — no need to repeat code.
(c) To Make Programs Easier to Update
If something changes, you only need to edit the class (the blueprint), not every single place you used the code.
(d) To Make Code More Real-World
Classes help you think like real life:
-
A Car has features (attributes) like color and speed.
-
It also has actions (methods) like move(), stop(), start().
Python classes make it easy to describe things that way.
(e) For Teamwork
When many people work on one project, using classes makes the program neat, so everyone can understand where each part belongs.
π» Example:
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print("Hello, my name is", self.name)
# Create (or “instantiate”) two students
s1 = Student("Amina", 12)
s2 = Student("John", 14)
s1.greet() # Output: Hello, my name is Amina
s2.greet() # Output: Hello, my name is John
Here:
-
Studentis the class (blueprint) -
s1ands2are objects (real students)
π Summary:
| Reason | Why It’s Important |
|---|---|
| Organization | Keeps big projects neat |
| Reusability | Saves time — use code again |
| Easy Updates | Change one place, not many |
| Real-World Thinking | Models real things like students, cars, etc. |
| Teamwork | Helps many people understand and work together |
MAIN PARTS OF A CLASS IN PYTHON
A class has three main parts:
-
Attributes (Variables)
-
Methods (Functions inside the class)
-
Constructor (
__init__method)
Let’s explain each one in detail π
π§© 1. Attributes (Variables inside a class)
Meaning:
Attributes are like the features or properties that belong to an object.
They are used to store information about each object created from the class.
Example (Real life):
If you have a class called Student, the attributes could be:
-
name
-
age
-
school
That means every student object will have these pieces of information.
Python Example:
class Student:
def __init__(self, name, age):
self.name = name # attribute
self.age = age # attribute
Here,
name and age are attributes — they describe each student.
⚙️ 2. Methods (Functions inside a class)
Meaning:
Methods are the actions or behaviors that an object can perform.
They are just like normal functions, but they live inside a class.
Example (Real life):
For a Student class:
-
A student can read
-
A student can write
-
A student can introduce himself
Those are methods.
Python Example:
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def introduce(self):
print("Hello, my name is", self.name, "and I am", self.age, "years old.")
When you call introduce(), that’s a method action.
πͺ 3. Constructor (__init__ method)
Meaning:
A constructor is a special method that runs automatically when you create a new object.
It helps you set up the initial information (attributes) for the object.
Example (Real life):
When a new student is admitted, you immediately record their name and age.
That process of setting up is like the constructor.
Python Example:
class Student:
def __init__(self, name, age): # constructor
self.name = name
self.age = age
Whenever you create a new student like this:
s1 = Student("Amina", 12)
The __init__ (constructor) runs automatically and gives the object its name and age.
π» FULL EXAMPLE:
class Student:
# Constructor
def __init__(self, name, age):
self.name = name # Attribute 1
self.age = age # Attribute 2
# Method
def introduce(self):
print(f"My name is {self.name}, and I am {self.age} years old.")
# Create two students (objects)
s1 = Student("Amina", 12)
s2 = Student("John", 14)
# Call the method
s1.introduce()
s2.introduce()
Output:
My name is Amina, and I am 12 years old.
My name is John, and I am 14 years old.
π§ Summary Table
| Part | Meaning | Example | Use |
|---|---|---|---|
| Attribute | Information about the object | name, age | Store data |
| Method | Action of the object | introduce(), read() | Perform task |
| Constructor | Special setup method | __init__ |
Give object its first data |
8. Class Work / Practice
1. Create
a class Bus and
make an object danfo1.
2. Create
a class Phone with
attributes brand
and color, print
them.
3. Create
a class Market
with method open_market()
that prints "Market is
open!".
9. Homework / Assignment
1. Create
a class Student
with name and score, make 2 objects.
2. Add
method grade() →
return "Pass"
if score ≥ 50, else "Fail".
3. Create
a class FoodVendor
with attribute food_type
and method sell_food()
→ print what they are selling.
10. Summary Table
|
Term |
Meaning
(Nigeria examples) |
|
Class |
Plan or blueprint (like bus design) |
|
Object |
Real thing from class (like actual danfo/BRT) |
|
Attribute |
Property of object (name, age, brand, color) |
|
Method |
Action object can do (ring, bark, sell_food) |
|
|
Special function to set attributes when creating object |
✅ Tips for Students
· Think class = plan, object = real thing
· Use attributes = details, methods = actions
· Examples from school, market, bus, phone make it easy to understand
Week 3: Modules, Packages, and File Handling
Sure! Let’s explain Python modules in simple Nigerian English π
1. What is a Module?
Meaning:
A module is like a box of code that contains functions, variables, and classes.
Instead of writing all your code in one file, you can organize code into separate modules and reuse them anywhere in your program.
Think of it like this:
-
You have a kitchen (your program)
-
A module is a cupboard with spices, pots, and pans (functions and classes)
-
You just go to the cupboard (module) whenever you need something instead of cooking everything from scratch.
πΉ 2. Why We Use Modules
-
Reusability – Write once, use anywhere.
-
Organization – Keeps your code neat and clean.
-
Easy Maintenance – Fix a bug in the module, and all programs using it get fixed automatically.
-
Sharing – You can share your module with others without giving them your whole program.
πΉ 3. Types of Modules
-
Built-in Modules – Python already has them.
Example:math,random,datetime -
External Modules – You can install them using
pip.
Example:numpy,pandas,requests -
Custom Modules – You create them yourself.
Example: You make a filemy_module.pyand use it in another program.
πΉ 4. How to Use a Module
(a) Using a Built-in Module
Python Built-in Modules
1 What are Built-in Modules?
Built-in modules are Python packages that come with Python automatically.
You don’t need to install them — they’re ready to use.
They provide common functionality, like math operations, random numbers, and date/time handling.
2 Why Use Built-in Modules?
Save time — no need to write everything from scratch.
Make programming easier and more efficient.
Very useful in Django for things like date handling, math calculations, and random data.
3 Examples of Built-in Modules
math
Used for mathematical operations like square root, power, sine, cosine.
import math
print(math.sqrt(16)) # Output: 4.0
print(math.pow(2, 3)) # Output: 8.0
print(math.pi) # 3.141592653589793
Here, math is a module, and sqrt() and pi are functions/variables inside it.
(b) Using Only Part of a Module
from math import sqrt,pi
print(sqrt(25)) # 5.0
print(pi) # 3.141592653589793
b) random
Used to generate random numbers or select random items.
import random
print(random.randint(1, 10)) # Random integer between 1 and 10
print(random.choice(['apple','banana','mango'])) # Random item from list
c) datetime
Used to handle dates and times.
from datetime import datetime
now = datetime.now()
print(now) # Shows current date and time
other common built in modules
os
datetime
json
logging
π§© 1️⃣ os
What it is:
A module that lets Python interact with the computer’s operating system.
Uses:
Create, read, and delete folders or files
Get or change the current working directory
Set file paths in Django projects
π 2️⃣ datetime
What it is:
A module for working with dates and times.
Uses:
Get the current date and time
Format or calculate dates
Record when data is created or updated in Django
πΎ 3️⃣ json
What it is:
A module for handling data in JSON format (used on the web).
Uses:
Convert Python data to JSON (for web APIs)
Convert JSON data back to Python
Send and receive data between Django and JavaScript
π§Ύ 4️⃣ logging
What it is:
A module for recording messages and errors that occur while a program runs.
Uses:
Track what your app is doing
Save errors and warnings to a log file
Debug Django applications safely
4. Classwork Idea
- Use math to calculate the square of 5
- Use random to pick a random fruit from a list of 5 fruits
- Use datetime to print today’s date
5 Assignment Idea
Write a Python program that:
- Uses math to calculate the area of a circle (radius = 7)
- Uses random to generate 3 random numbers between 1–100
- Uses datetime to print the current year, month, and day
Using External Modules in Python
1️⃣ What are External Modules?
-
External modules are Python packages that are not built into Python.
-
They provide extra functionality like math operations, data handling, or web requests.
-
Examples: numpy, pandas, requests
2️⃣ Why Use External Modules?
-
They save time — no need to write everything from scratch.
-
They allow you to do advanced tasks easily, like data analysis or web requests.
3️⃣ How to Install External Modules
Python uses pip, the package installer, to install external modules.
Command:
pip install module_name
Example 1: Install numpy
pip install numpy
Example 2: Install pandas
pip install pandas
Example 3: Install requests
pip install requests
4️⃣ How to Use Them in Python
After installing, you import the module in your code:
Example 1: Using numpy
import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr)
Explanation:
-
import numpy as np → imports numpy and lets you use np as a shortcut
-
np.array([1,2,3,4]) → creates an array
NumPy: Complete Beginner Guide
1. What is NumPy?
-
NumPy = Numerical Python
-
A Python module used for mathematical and scientific computing
-
Allows you to work with arrays and perform fast calculations
-
Type: External module → install with pip install numpy
2. Why Learn NumPy?
-
Faster than Python lists for calculations
-
Handles 1D arrays and 2D matrices
-
Supports mathematical, statistical, and linear algebra operations
-
Works with Pandas, Matplotlib, and other data tools
3. How to Use NumPy
Step 1: Install NumPy
pip install numpy
Step 2: Import NumPy
import numpy as np
Explanation:
-
Imports NumPy and gives it the nickname np to type less.
4. Create a 1D Array
arr = np.array([1, 2, 3, 4, 5])
print(arr)
Explanation:
-
np.array([1,2,3,4,5]) → Creates a 1-dimensional array
-
arr → Stores the array
-
print(arr) → Displays the array
Output:
[1 2 3 4 5]
5. Create a 2D Array
arr2d = np.array([[1,2,3],[4,5,6]])
print(arr2d)
Explanation:
-
A list of lists becomes a 2-dimensional array (matrix)
-
arr2d → Stores the 2D array
Output:
[[1 2 3]
[4 5 6]]
6. Array Operations
print("Sum:", np.sum(arr))
print("Mean:", np.mean(arr))
print("Max:", np.max(arr))
print("Min:", np.min(arr))
print("Square Root:", np.sqrt(arr))
Explanation:
-
np.sum(arr) → Adds all elements
-
np.mean(arr) → Finds average
-
np.max(arr) → Finds largest value
-
np.min(arr) → Finds smallest value
-
np.sqrt(arr) → Calculates square root for each element
Output:
Sum: 15
Mean: 3.0
Max: 5
Min: 1
Square Root: [1. 1.41421356 1.73205081 2. 2.23606798]
7. Reshape an Array
arr_1d = np.arange(16)
arr_4x4 = arr_1d.reshape(4,4)
print(arr_4x4)
Explanation:
-
np.arange(16) → Creates array from 0 to 15
-
.reshape(4,4) → Reshapes 1D array into 4x4 2D array
Output:
[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]
[12 13 14 15]]
8. Classwork (Solved Examples)
Exercise 1: Create a 1D array [10,20,30,40,50]
arr1 = np.array([10,20,30,40,50])
print(arr1)
Exercise 2: Sum, Mean, Max, Min
print("Sum:", np.sum(arr1))
print("Mean:", np.mean(arr1))
print("Max:", np.max(arr1))
print("Min:", np.min(arr1))
Exercise 3: Create 2D array [[1,2,3],[4,5,6]] and print shape
arr2 = np.array([[1,2,3],[4,5,6]])
print("Array:\n", arr2)
print("Shape:", arr2.shape)
Exercise 4: Add 5 to every element
arr_plus5 = arr1 + 5
print(arr_plus5)
9. Assignment (Solved Examples)
Assignment 1: Create 3x3 array of ones
arr_ones = np.ones((3,3))
print(arr_ones)
Assignment 2: Multiply by random numbers 1–10
random_nums = np.random.randint(1,11,(3,3))
arr_mult = arr_ones * random_nums
print("Random Array:\n", random_nums)
print("Multiplied with Ones:\n", arr_mult)
Assignment 3: Row sum and Column sum
print("Row sums:", np.sum(arr_mult, axis=1))
print("Column sums:", np.sum(arr_mult, axis=0))
Assignment 4: Reshape 1D array 0–15 to 4x4
arr_range = np.arange(16)
arr_4x4 = arr_range.reshape(4,4)
print(arr_4x4)
10. Summary Notes
-
NumPy = Numerical Python → Arrays + Math
-
1D array → np.array([..])
-
2D array → np.array([[..],[..]])
-
Basic operations → np.sum(), np.mean(), np.max(), np.min(), np.sqrt()
-
Reshape → arr.reshape(rows, cols)
-
arange() → Create a sequence of numbers
Example 2: Using pandas
import pandas as pd
data = pd.DataFrame({
"Name": ["Raheem", "Ali", "Sara"],
"Age": [24, 22, 23]
})
print(data)
Explanation:
-
pd.DataFrame → creates a table-like structure
-
Useful for handling data in Django projects or APIs
Pandas: Complete Beginner Guide
1. What is Pandas?
-
Pandas is a Python module for data analysis and data manipulation.
-
Allows you to work with tables (DataFrames) and columns (Series) easily.
-
Type: External module → must install with pip install pandas.
2. Why Learn Pandas?
-
Works with large datasets efficiently
-
Makes data analysis easy (mean, sum, max, min, filtering)
-
Can read/write CSV, Excel, JSON, SQL
-
Supports data cleaning and manipulation
3. How to Use Pandas
Step 1: Install Pandas
pip install pandas
Step 2: Import Pandas
import pandas as pd
Explanation:
-
import pandas as pd → Imports Pandas and gives it the nickname pd so we can type less.
4. Create a Series
s = pd.Series([5, 10, 15, 20])
print(s)
Explanation:
-
pd.Series([5,10,15,20]) → Creates a 1D array with labels (index)
-
s → Stores the Series
-
print(s) → Shows the Series
Output:
0 5
1 10
2 15
3 20
dtype: int64
5. Create a DataFrame
data = {
"Name": ["John", "Mary", "Paul"],
"Age": [18, 19, 20],
"Grade": ["A", "B", "A"]
}
df = pd.DataFrame(data)
print(df)
Explanation:
-
data = {...} → A dictionary where keys = column names, values = list of column data
-
pd.DataFrame(data) → Converts dictionary into 2D table
-
df → Stores the DataFrame
-
print(df) → Displays the table
Output:
Name Age Grade
0 John 18 A
1 Mary 19 B
2 Paul 20 A
6. View Data
print(df.head(2)) # Shows first 2 rows
print(df.tail(1)) # Shows last row
Explanation:
-
head(n) → View first n rows
-
tail(n) → View last n rows
7. Access Columns
print(df["Age"])
Explanation:
-
df["Age"] → Selects the Age column as a Series
-
You can now perform calculations on this column
8. Basic Calculations
print("Average Age:", df["Age"].mean())
print("Max Age:", df["Age"].max())
print("Min Age:", df["Age"].min())
Explanation:
-
.mean() → Finds average
-
.max() → Finds largest value
-
.min() → Finds smallest value
9. Sort Data
df_sorted = df.sort_values("Age")
print(df_sorted)
Explanation:
-
df.sort_values("Age") → Sorts rows by the Age column in ascending order
10. Filter Data
grade_a_students = df[df["Grade"] == "A"]
print(grade_a_students)
Explanation:
-
df["Grade"] == "A" → Creates True/False for rows with Grade A
-
df[...] → Filters DataFrame based on condition
Output:
Name Age Grade
0 John 18 A
2 Paul 20 A
11. Save DataFrame
df.to_csv("students_output.csv", index=False)
Explanation:
-
Saves DataFrame to CSV file
-
index=False → Prevents row numbers from being saved
12. Classwork (Solved Examples)
-
Create a Series [5,10,15,20]
s = pd.Series([5, 10, 15, 20])
print(s)
-
Create DataFrame of 3 students
data = {"Name": ["John","Mary","Paul"], "Age": [18,19,20], "Grade": ["A","B","A"]}
df = pd.DataFrame(data)
print(df)
-
View first 2 rows
print(df.head(2))
-
Average age
print(df["Age"].mean())
-
Sort by Age
df_sorted = df.sort_values("Age")
print(df_sorted)
13. Assignment (Solved Examples)
Task: Create DataFrame of 5 students
data = {
"Name": ["Alice","Bob","Charlie","David","Eva"],
"Age": [20,22,21,19,23],
"Grade": ["A","B","A","C","B"],
"Marks": [85,70,90,60,75]
}
df = pd.DataFrame(data)
print(df)
Highest Marks and Student
max_marks = df["Marks"].max()
student = df[df["Marks"] == max_marks]["Name"].values[0]
print("Highest Marks:", max_marks)
print("Student:", student)
Average Marks
print("Average Marks:", df["Marks"].mean())
Students with Grade 'A'
grade_a_students = df[df["Grade"] == "A"]
print(grade_a_students)
Save to CSV
df.to_csv("students_output.csv", index=False)
✅ Summary Notes for Students
-
Series → 1D labeled array
-
DataFrame → 2D table
-
head()/tail() → View rows
-
Column selection → Access data
-
mean()/max()/min() → Basic calculations
-
Sorting and filtering → Organize or select data
-
to_csv() → Save for later
Example 3: Using requests
import requests
response = requests.get("https://api.github.com")
print(response.status_code)
Explanation:
-
requests.get(url) → sends a GET request to a website/API
-
response.status_code → shows if the request was successful
Before Request Let talk about file
Python File Handling – Complete Student Notes
1. What is File Handling?
-
File handling is how Python reads from or writes to files stored on your computer.
-
Files can be text files (.txt), CSV files (.csv), or binary files (.jpg, .png).
2. Why Use File Handling?
-
To store data permanently (so it’s not lost when the program stops)
-
To read data from saved files
-
To process and save results of programs
3. How to Work with Files (Line by Line)
3.1 Opening a File
file = open("example.txt", "r")
Explanation:
-
open() → Opens a file
-
"example.txt" → Name of the file
-
"r" → Mode: read (r), write (w), append (a)
3.2 Reading a File
content = file.read()
print(content)
file.close()
Explanation:
-
file.read() → Reads the entire content of the file
-
print(content) → Displays the content
-
file.close() → Closes the file to free resources
3.3 Writing to a File
file = open("example.txt", "w")
file.write("Hello, Python!")
file.close()
Explanation:
-
"w" → Open file in write mode (overwrites existing content)
-
file.write("...") → Writes the text to the file
-
file.close() → Always close the file
3.4 Appending to a File
file = open("example.txt", "a")
file.write("\nThis line is added.")
file.close()
Explanation:
-
"a" → Append mode, adds text without erasing existing content
-
\n → Newline character
3.5 Using with Statement (Better Practice)
with open("example.txt", "r") as file:
content = file.read()
print(content)
Explanation:
-
with open(...) as file: → Automatically closes file after use
-
Safer and cleaner than manually calling file.close()
4. Classwork (Practice)
-
Create a file called students.txt and write 3 student names into it.
-
Read the file and print the contents line by line.
-
Append a new student name to the file.
-
Use with open() to read the file and display all names.
5. Assignment
-
Create a text file marks.txt and write 5 students’ marks.
-
Read the file, calculate total and average marks, and display them.
-
Append 1 more student mark and update the total and average.
-
Use with open() for all reading and writing tasks.
✅ Key Notes
-
Modes:
-
"r" → Read
-
"w" → Write (overwrite)
-
"a" → Append
-
"rb", "wb" → Binary read/write
-
Always close files or use with open()
-
read() → Reads all content
-
readline() → Reads one line
-
readlines() → Reads all lines as a list
Perfect! Let’s make a simple analogy between Python file handling and the requests module so it’s easy to understand.
File Handling vs Requests Analogy
Concept
File Handling
Requests
Source
File on your computer (example.txt)
Data on a server/website (https://api.example.com/data)
Action
open("file.txt", "r") → read file
requests.get(url) → fetch data from server
Writing
open("file.txt", "w") → write file
requests.post(url, data=data) → send data to server
Reading Content
file.read() → string from file
response.text → string from server
Using JSON
N/A (unless file has JSON)
response.json() → converts JSON response to dictionary
Closing / Cleanup
file.close() or with open()
No explicit close needed; requests handles it automatically
Analogy
Reading/writing a local document
Reading/writing online “document” from a server
Example: File → Requests Analogy
File Reading
# File
with open("students.txt", "r") as file:
data = file.read()
print(data)
GET Request
# Requests
import requests
response = requests.get("https://api.example.com/students")
data = response.text
print(data)
File Writing
# File
with open("students.txt", "w") as file:
file.write("John, Mary, Paul")
POST Request
# Requests
import requests
student_data = {"name": "John", "age": 20}
response = requests.post("https://api.example.com/add_student", json=student_data)
print(response.status_code)
Classwork / Practice
-
Create a file data.txt and write "Hello World" in it.
-
Read the file and print the content.
-
Use requests.get() to fetch "https://httpbin.org/get" and print the response.
-
Use requests.post() to send {"name":"Test"} to "https://httpbin.org/post" and print the response.
Assignment
-
Read a file of student marks and calculate total and average.
-
Fetch a JSON dataset from a server (GET request) and display it.
-
Send a small dictionary of your own data using POST to "https://httpbin.org/post" and print the result.
-
Explain how reading a file is like GET and writing a file is like POST in one sentence.
✅ Key Takeaway:
File handling = local data, Requests = remote data
Reading = GET, Writing = POST
Python requests Module
1. What is requests?
-
requests is a Python module used to send HTTP requests.
-
You can get data from websites, send data, or interact with APIs.
-
Type: External module → install using pip install requests.
2. Why Use requests?
-
Makes working with HTTP simple
-
Send GET and POST requests easily
-
Retrieve data from web APIs in JSON or text format
-
Handle headers, cookies, and parameters
3. Install and Import
pip install requests
import requests
-
import requests → Makes all functions of the requests module available
4. Sending a GET Request
response = requests.get("https://api.github.com")
print(response.status_code) # HTTP response code (200 = success)
print(response.text) # Response content
Explanation:
-
requests.get(url) → Sends a GET request to the URL
-
response.status_code → HTTP status code (200 = OK, 404 = Not Found)
-
response.text → Content of the response as string
Sending a GET Request in Python
1. What is a GET Request?
-
GET is a type of HTTP request used to retrieve data from a server.
-
When you open a website in your browser, your browser is actually sending a GET request to the website’s server.
-
In Python, we can do this programmatically using the requests module.
2. Why Use GET Requests?
-
To fetch data from websites or APIs
-
To read JSON, HTML, or text from a server
-
To automate data retrieval without opening a browser
3. How to Send a GET Request
Step 1: Import the requests module
import requests
-
This allows you to use all functions in the requests module.
Step 2: Send a GET request
response = requests.get("https://api.github.com")
Explanation:
-
requests.get(url) → Sends a GET request to the URL
-
response → Stores the server’s reply
Step 3: Check Response Status
print(response.status_code)
Explanation:
-
response.status_code → Returns the HTTP status code
-
200 → OK, request successful
-
404 → Not Found
-
500 → Server error
Step 4: Read Response Content
print(response.text)
Explanation:
-
response.text → Returns the content of the page or API as a string
Step 5: Parse JSON Data (if API returns JSON)
data = response.json()
print(data)
Explanation:
-
.json() → Converts response to a Python dictionary
-
Useful for working with API data
4. Example of a GET Request
import requests
# Send GET request
response = requests.get("https://api.github.com")
# Check if request was successful
if response.status_code == 200:
print("Request successful!")
data = response.json() # Convert to Python dictionary
print(data) # Print API data
else:
print("Request failed with status code:", response.status_code)
Output (example):
Request successful!
{'current_user_url': 'https://api.github.com/user', 'current_user_authorizations_html_url': ... }
5. Classwork / Practice
-
Send a GET request to https://httpbin.org/get and print response.text.
-
Send a GET request to https://api.ipify.org?format=json and print your public IP address.
-
Check response status codes for any URL and print "Page Found" if 200 or "Page Not Found" if 404.
6. Key Notes
-
GET request = fetch data (do not change server data)
-
Always check status code before using the response
-
Use .text for string content, .json() for JSON content
-
Can include parameters in the URL:
response = requests.get("https://httpbin.org/get?name=John&age=25")
-
The server will see name=John and age=25 as query parameters
5. Sending a POST Request
data = {"username": "test", "password": "12345"}
response = requests.post("https://httpbin.org/post", data=data)
print(response.status_code)
print(response.json()) # Converts response to JSON
Explanation:
-
requests.post(url, data=data) → Sends data to the server
-
response.json() → Converts response content to Python dictionary
6. Classwork Examples
-
Send a GET request to https://httpbin.org/get and print response text.
-
Send a POST request with name and age to https://httpbin.org/post and print JSON response.
-
Check the status code of https://api.github.com
7. Assignment Examples
-
Retrieve your IP address using https://api.ipify.org?format=json
-
Send login data (dummy) to https://httpbin.org/post and print response.
-
Handle a 404 page by checking response.status_code and printing a message "Page Not Found" if 404.
✅ Summary Notes
-
requests = HTTP client for Python
-
GET → Retrieve data
-
POST → Send data
-
Useful for APIs and web scraping
-
Always check status code before using response
Sending a POST Request in Python
1. What is a POST Request?
-
POST is a type of HTTP request used to send data to a server.
-
Unlike GET, POST is used to create, update, or submit data on the server.
-
Common uses:
-
Submitting a form online
-
Logging in to a website
-
Sending data to an API
2. Why Use POST Requests?
-
To send data securely
-
To submit forms or JSON data
-
Works with APIs that accept user input
3. How to Send a POST Request
Step 1: Import the requests module
import requests
Step 2: Create Data to Send
data = {"username": "testuser", "password": "12345"}
Explanation:
-
data is a Python dictionary that contains the information you want to send
Step 3: Send POST Request
response = requests.post("https://httpbin.org/post", data=data)
Explanation:
-
requests.post(url, data=data) → Sends the data to the server at the given URL
-
response → Stores the server’s reply
Step 4: Check Response Status
print(response.status_code)
-
200 → Success
-
Other codes → Something went wrong
Step 5: View Response Content
print(response.text) # Raw response
print(response.json()) # Convert JSON response to Python dictionary
Explanation:
-
.text → Returns content as string
-
.json() → Returns content as Python dictionary (useful for APIs)
4. Example of a POST Request
import requests
# Data to send
data = {"username": "testuser", "password": "12345"}
# Send POST request
response = requests.post("https://httpbin.org/post", data=data)
# Check if request was successful
if response.status_code == 200:
print("POST request successful!")
print(response.json()) # Print JSON response from server
else:
print("Request failed with status code:", response.status_code)
Output (example):
POST request successful!
{
"args": {},
"data": "",
"files": {},
"form": {
"password": "12345",
"username": "testuser"
},
"headers": { ... },
"json": null,
"url": "https://httpbin.org/post"
}
5. POST with JSON Data
import requests
import json
data = {"username": "testuser", "password": "12345"}
response = requests.post("https://httpbin.org/post", json=data)
print(response.json())
Explanation:
-
json=data → Sends data as JSON instead of form-encoded
-
Useful for APIs that expect JSON input
6. Classwork / Practice
-
Send a POST request to https://httpbin.org/post with name and age fields.
-
Send login details (username & password) using JSON and print server response.
-
Check the status code and print "Success" if 200 or "Failed" if not.
7. Key Notes
-
POST request = send data (unlike GET, which retrieves data)
-
Use data= for form data
-
Use json= for JSON data
-
Always check status code before processing response
5️⃣ Classwork Idea
-
Install numpy and pandas using pip
-
Create a numpy array of 5 numbers and print it
-
Create a pandas DataFrame with 2 columns: Name and Age, and print it
6️⃣ Assignment Idea
-
Install requests
-
Fetch data from https://api.github.com
-
Print the first 200 characters of the response
(c) Creating Your Own Module
-
Create a file called
my_module.py
# my_module.py
def greet(name):
print("Hello", name)
def add(a, b):
return a + b
-
Use it in another file
# main.py
import my_module
my_module.greet("Amina") # Hello Amina
print(my_module.add(5, 3)) # 8
πΉ 5. Shortcut: Give Module a Nickname
import math as m
print(m.sqrt(64)) # 8.0
✅ Summary Table
| Term | Meaning | Example |
|---|---|---|
| Module | File with code | math, my_module.py |
| Function in Module | Action inside module | sqrt(), add() |
| Built-in Module | Comes with Python | random, datetime |
| Custom Module | You create it | my_module.py |
Classwork:
-
Create a package
mypackagewith 2 modules. Write one function in each module.
Assignment:
-
Import functions from both modules in a main file and use them.
π§ WEEK LESSON PLAN: PYTHON PACKAGES (Simple Version)
π
Days: Monday – Friday
π©π« Teacher-centered + Student practice
π― Goal: Help students understand, create, and use Python packages confidently.
π MONDAY – Introduction to Python Packages
π§ What to Teach
-
A module is one Python file (
.py) that has code. -
A package is a folder that contains many modules.
-
A package always has a special file named
__init__.py.
π©π« Teacher Explanation
“A package helps us organize our Python programs neatly so we don’t keep all code in one file.”
π» Example:
Create a folder called mathpackage
Inside the folder, make these files:
add.py
def add(a, b):
return a + b
subtract.py
def subtract(a, b):
return a - b
main.py
from mathpackage import add, subtract
print(add.add(3, 2))
print(subtract.subtract(5, 1))
✅ Output:
5
4
✍️ Classwork
Ask students to create a folder called greetpackage with one file greet.py that prints “Hello, World!”
π TUESDAY – Why and Where We Use Packages
π§ What to Teach
-
We use packages to keep our code organized.
-
Packages make it easy to share and reuse code.
-
Django uses many packages (e.g.,
django.urls,django.db).
π» Example:
Create a folder called schoolpackage
student.py
def info(name):
print("Student name is:", name)
result.py
def grade(score):
if score >= 50:
print("Pass")
else:
print("Fail")
main.py
from schoolpackage import student, result
student.info("Raheem")
result.grade(70)
✅ Output:
Student name is: Raheem
Pass
✍️ Classwork
Create a package called shop with a file that prints the name and price of an item.
π WEDNESDAY – Using Built-in and External Packages
π§ What to Teach
-
Python already comes with some packages like
mathandrandom. -
You can also install other packages using pip.
π» Example 1 (Built-in)
import random
print(random.randint(1, 10)) # prints a random number
✅ Output Example:
7
π» Example 2 (Built-in)
import math
print(math.sqrt(16)) # square root of 16
✅ Output:
4.0
π» Example 3 (External)
Install with:
pip install requests
Then run:
import requests
page = requests.get("https://www.google.com")
print(page.status_code)
✅ Output:
200
✍️ Classwork
Ask students to use the math package to find the square root of 25.
π THURSDAY – Create and Use Your Own Package
π§ What to Teach
-
You can create your own package to use in other projects.
-
A package can contain many
.pyfiles.
π» Example Project: calc_tool
add.py
def add(a, b):
return a + b
multiply.py
def multiply(a, b):
return a * b
main.py
from calc_tool import add, multiply
print(add.add(4, 3))
print(multiply.multiply(5, 2))
✅ Output:
7
10
✍️ Student Project
Create a package called area_package
Inside, create:
-
rectangle.py→ calculate area = length × width -
circle.py→ calculate area = Ο × r²
Then call both from main.py.
π FRIDAY – Test and Review
✍️ Test (5 Questions)
-
What is a package in Python?
-
What is the difference between a module and a package?
-
Why do we use packages?
-
Write code to import
studentfrom a package calledschoolpackage. -
Create a simple package that has a module to print the square of a number.
✅ Answers
-
A package is a folder that contains one or more Python files (
.py) and a special__init__.pyfile. -
A module is one file; a package is a group of files.
-
We use packages to organize, reuse, and share code easily.
from schoolpackage import student
mysquare/square.py
def sqr(x):
print(x * x)
main.py
from mysquare import square
square.sqr(5)
✅ Output:
25
π‘ Teacher Tips
-
Start every day with 10 minutes review.
-
Let students type and run code themselves.
-
Ask them to explain in their own words what each line does.
-
End Friday with a 10-minute class discussion on how Django uses packages.
π§© Topic: Library in Programming (Python)
π‘ Class Level: Beginner Python Students
π️ Duration: 1 hour
π§ Teaching Method: Student-Centered (learn-by-doing, discussion, examples, and group activity)
π·️ Lesson Objectives
By the end of this class, students should be able to:
-
Explain what a library is in programming.
-
Identify why libraries are used.
-
Import and use a simple Python library.
-
Create a small project using a library.
π£️ Introduction (10 mins)
Teacher asks:
“Have you ever used something made by someone else to make your work easier?”
Students respond (e.g., “Yes, like using a calculator or a template”).
Teacher explains:
A library in programming is like a collection of ready-made tools (functions and modules) created by others to help you solve problems faster.
π Main Content (25 mins)
1️⃣ What is a Library?
A library is a collection of pre-written code that you can use in your programs instead of writing everything from scratch.
2️⃣ Why We Use Libraries
-
To save time ⏱️
-
To reuse tested and reliable code
-
To make work easier (e.g., math, data analysis, web apps)
3️⃣ Examples of Python Libraries
| Library | Purpose |
|---|---|
math |
For mathematical functions |
random |
For generating random numbers |
datetime |
For working with date and time |
os |
For interacting with your computer system |
requests |
For working with the internet (APIs) |
django |
For building websites |
π» Practical (Hands-on Example)
Teacher Demonstration:
# Using the math library
import math
print("Square root of 16 is:", math.sqrt(16))
print("Value of Pi is:", math.pi)
Students try:
import random
print("Random number between 1 and 10:", random.randint(1, 10))
π§© Classwork
Ask each student to:
-
Import the
datetimelibrary. -
Print today’s date.
import datetime
print("Today's date is:", datetime.date.today())
π§ Mini Project
Create a simple "Lucky Number App" using random.
import random
name = input("Enter your name: ")
lucky_number = random.randint(1, 100)
print(name, ", your lucky number today is:", lucky_number)
π§Ύ Friday Test (with answers)
1️⃣ What is a library in Python?
Answer: A collection of pre-written code used to perform common tasks easily.
2️⃣ Name two reasons why we use libraries.
Answer: To save time and reuse reliable code.
3️⃣ Write a code that prints a random number between 5 and 20.
Answer:
import random
print(random.randint(5, 20))
4️⃣ Which library is used to work with dates and time?
Answer: datetime
Excellent π
Let’s continue our student-centered teaching with the next topic:
π§© Topic: Frameworks in Python
π‘ Class Level: Beginner–Intermediate
π️ Duration: 1 hour
π§ Teaching Method: Student-Centered (discussion, demo, and practice)
π― Lesson Objectives
By the end of this lesson, students should be able to:
-
Explain what a framework is in Python.
-
Differentiate between a library and a framework.
-
Mention examples of popular Python frameworks.
-
Build a simple example using a mini framework (like Flask).
π£️ Introduction (10 mins)
Teacher asks:
“If libraries help us with small tools, what if we need a full structure for our program — like building a complete house instead of using just one tool?”
Students respond.
Teacher explains:
A framework is like a blueprint or foundation that helps you build big projects faster — especially websites, mobile apps, or APIs — using rules and ready-made structures.
π Main Content (25 mins)
1️⃣ What is a Framework?
A framework is a collection of libraries and tools that gives structure to your program.
It decides how you should build your project.
π§± Example:
-
Libraries = tools (hammer, nails, wood).
-
Framework = house plan (where tools are used in a structured way).
2️⃣ Difference Between Library and Framework
| Feature | Library | Framework |
|---|---|---|
| Control | You control when to use it | Framework controls your code flow |
| Purpose | Small helper tool | Complete project structure |
| Example | math, random |
Django, Flask |
| Use | Specific tasks | Large applications |
3️⃣ Examples of Python Frameworks
| Framework | Used For |
|---|---|
| Django | Full web development framework |
| Flask | Lightweight web app framework |
| FastAPI | Building fast APIs |
| TensorFlow | Machine learning framework |
| Kivy | Mobile app framework |
π» Practical: Build a Simple Flask App
Teacher demonstrates:
# Step 1: Install Flask (only once)
# pip install flask
# Step 2: Create a simple web app
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return "Hello Students! Welcome to Python Frameworks."
# Step 3: Run
if __name__ == '__main__':
app.run(debug=True)
Students run and open:
π http://127.0.0.1:5000
They should see the message on their browser.
π§© Classwork
Ask each student to:
-
Change the message in the Flask app to their name (e.g., “Hello Raheem, welcome back!”)
-
Add another route
/aboutthat says “This is my first web app.”
π‘ Mini Project
Build a “Student Greeting Web App”:
-
When the user goes to
/, it says “Welcome to my App!” -
When the user goes to
/student, it says “Hello student, have a great day!”
π§Ύ Friday Test (with answers)
1️⃣ What is a framework in Python?
Answer: A structure that provides tools and rules to build big applications easily.
2️⃣ Give two examples of frameworks in Python.
Answer: Django, Flask.
3️⃣ Mention one difference between a library and a framework.
Answer: In a library, you control the code flow; in a framework, it controls you.
4️⃣ What command is used to install Flask?
Answer: pip install flask
5️⃣ What is the URL of a local Flask app?
Answer: http://127.0.0.1:5000
1. What is File Handling?
Meaning:
File handling is Python’s way of reading from and writing to files on your computer.
Think of it like this:
-
A file is like a notebook.
-
You can write in it, read from it, or update it using Python.
Why it’s important:
-
Save data for later (like student names, scores, or records)
-
Automate reports
-
Store and read large information without typing everything again
πΉ 2. Types of File Operations
-
Open a file – To read, write, or append
-
Read a file – Get information from it
-
Write to a file – Add new information
-
Append to a file – Add information at the end without removing old data
-
Close a file – Always close after use to save changes
πΉ 3. How to Open a File
file = open("myfile.txt", "mode")
Sure! Let’s break it down step by step in simple Nigerian English π
file = open("myfile.txt", "mode")
This line is used in Python to open a file so you can read from it, write to it, or append data.
πΉ Components Explained
file
This is a variable where we store the file object.
You can name it anything, like myfile, f, or data.
Example:
f = open("myfile.txt", "r")
open()
This is a built-in Python function that opens a file.
It takes two main arguments: the file name and the mode.
"myfile.txt"
This is the name of the file you want to work with.
It must be in the same folder as your Python program, or you need the full path.
Example with path:
file = open("C:/Users/Raheem/Documents/myfile.txt", "r")
"mode"
Mode tells Python how you want to use the file.
Common modes:
Mode
Meaning
"r"
Read only (file must exist)
"w"
Write (creates file if not exist, replaces old content)
"a"
Append (adds new content at the end)
"r+"
Read and write
"x"
Create new file (fails if file exists)
Example:
file = open("myfile.txt", "r") # Open for reading
file = open("myfile.txt", "w") # Open for writing
Using the File
After opening, you can read or write:
file.write("Hello Nigeria!")
content = file.read()
Always close the file after use:
file.close()
πΉ Shortcut: with Statement
This automatically closes the file for you:
with open("myfile.txt", "r") as file:
content = file.read()
print(content)
In short:
file = open("myfile.txt", "mode") → open a file called myfile.txt in a certain mode and store it in a variable called file so you can work with it.
Modes:
| Mode | Meaning |
|---|---|
"r" |
Read only (file must exist) |
"w" |
Write (creates file if not exist, replaces old content) |
"a" |
Append (adds to the end) |
"r+" |
Read & write |
"x" |
Create new file (fails if file exists) |
πΉ 4. Reading Files
# Open file in read mode
file = open("myfile.txt", "r")
# Read whole file
content = file.read()
print(content)
# Read line by line
file.seek(0) # go back to start
for line in file:
print(line)
# Close file
file.close()
πΉ 5. Writing to Files
# Open file in write mode
file = open("myfile.txt", "w")
file.write("Hello Nigeria!\n")
file.write("Python is fun!\n")
file.close()
Note: Using "w" replaces old content. Use "a" to keep old content.
# Append mode
file = open("myfile.txt", "a")
file.write("Adding more lines...\n")
file.close()
πΉ 6. Using with Statement (Recommended)
Python allows a shortcut that automatically closes the file:
# Writing to a file
with open("myfile.txt", "w") as file:
file.write("Hello, this is my file!")
# Reading from a file
with open("myfile.txt", "r") as file:
content = file.read()
print(content)
πΉ 7. Example: Student Records
# Writing student names to a file
students = ["Amina", "John", "Mary"]
with open("students.txt", "w") as file:
for student in students:
file.write(student + "\n")
# Reading student names
with open("students.txt", "r") as file:
for line in file:
print("Student:", line.strip())
Output:
Student: Amina
Student: John
Student: Mary
✅ Summary Table
| Operation | Example | What it Does |
|---|---|---|
| Open File | open("file.txt", "r") |
Opens a file in mode r/w/a |
| Read File | file.read() |
Reads all content |
| Write File | file.write("text") |
Writes new content |
| Append File | open("file.txt","a") |
Adds content at end |
| Close File | file.close() |
Closes file to save changes |
| With Statement | with open("file.txt","r") as f: |
Automatically handles open & close |
File handling is very important because after this, you can store and use data in real-life projects, like:
-
Student scores
-
Inventory lists
-
Logs for apps
Week 1 Day 1:
What is Django?
-
Django is a tool (framework) in Python used to make websites and web apps.
-
It helps you do everything in one place: manage databases, create pages, handle users, and forms.
Simple idea: Django helps you make websites without starting from scratch.
Why Use Django?
-
Fast Development – Has built-in tools, so you can make websites quickly.
-
Secure – Protects against attacks like hacking or stealing data.
-
Scalable – Can handle small or very big websites.
-
Admin Panel – Gives a ready-made dashboard to manage data.
-
Uses Python – Easy to learn and understand.
-
Organized – Lets you reuse code and keep your project clean.
-
Community – Lots of help and tutorials are available online.
When to Use Django?
-
When building websites that change with user input (blogs, dashboards).
-
When building web apps (like school portals or e-commerce).
-
When you want to finish a website fast.
-
When building big or growing projects.
-
When your app uses databases to store data.
Examples: Instagram, Pinterest, Mozilla, Washington Post
Practical Example / Demonstration for Students
Goal:
Understand what Django is and see it in action.
Step 1: Install Django
Ask students to open terminal or command prompt and type:
pip install django
-
Observation: Students should see Django installing.
-
Point: Django is a tool in Python to make websites.
Step 2: Start a Django Project
django-admin startproject mysite
cd mysite
-
Observation: A new folder
mysiteis created with project files. -
Point: Django organizes everything for your website automatically.
Step 3: Run the Server
python manage.py runserver
-
Open browser and go to
http://127.0.0.1:8000/ -
Observation: They see the Django welcome page.
-
Point: Django can show webpages easily without writing complex code.
Step 4: Open Admin Panel (Optional)
python manage.py createsuperuser
-
Go to
http://127.0.0.1:8000/admin/and log in. -
Observation: Ready-made admin dashboard appears.
-
Point: Django gives a built-in dashboard to manage data.
Classwork
-
Ask students to explain in their own words what Django is.
-
Let them install Django on their computer.
-
Run a project and show the welcome page in a browser.
-
Discuss the built-in tools like admin panel and project structure.
Assignment
-
Write a short answer: What is Django? Use simple words.
-
List 3 reasons why Django is good for making websites.
-
List 2 websites that use Django (examples: Instagram, Pinterest).
-
Try creating a Django project and take a screenshot of the welcome page.
Day 2:Django Components
-
Models – Handle data and databases.
-
Views – Handle logic and what to show.
-
Templates – Handle design and front-end.
-
URLs – Connect web addresses to views.
-
Admin – Dashboard to manage data.
-
MVT Architecture – Structure (Model-View-Template).
-
Middleware – Process requests and responses.
-
Forms – Collect user input.
-
ORM – Use Python to work with databases.
-
Security – Protect the app.
Absolutely! Let me explain how Django components work together using a Student Management System analogy in a simple, beginner-friendly way without long code.
How Django Works – Student Management System Example
1️⃣ Models – The Student Records
-
What it is: The place where all student data is stored.
-
Analogy: Think of it as your school’s register or database.
-
Each student has name, age, grade, and subjects.
-
-
Purpose: Keeps all student info organized so the system can access it easily.
2️⃣ Views – The Decision Maker
-
What it is: The part that decides what to show to the user.
-
Analogy: Imagine a school secretary:
-
You ask for a student’s report, and the secretary fetches the right info from the register.
-
-
Purpose: Gets data from the register (Model) and sends it to the report page (Template).
3️⃣ Templates – The Webpage
-
What it is: The design and layout of what the user sees.
-
Analogy: Think of a report card or a notice board:
-
Shows the student’s name, grade, and results in a readable format.
-
-
Purpose: Makes the data look nice and understandable, often using HTML, CSS, and JS.
4️⃣ URLs – The Address
-
What it is: The web address the user visits.
-
Analogy: Think of it as a classroom number or office door:
-
/students/→ list of all students -
/students/1/→ details of student with ID 1
-
-
Purpose: Directs the user to the right View for the right page.
5️⃣ How It All Works Together
-
User visits a page (URL) – e.g.,
/students/. -
URL maps to a View – decides which data to get.
-
View fetches data from Model – e.g., all students in the register.
-
View passes data to Template – student names, ages, and grades.
-
Template displays it in the browser with HTML structure, styled by CSS, maybe interactive with JS.
Visual Analogy – Student Management
| Component | School Analogy | What It Does |
|---|---|---|
| Model | Student Register | Stores student data |
| View | School Secretary | Fetches info and decides what to show |
| Template | Report Card / Notice Board | Shows data nicely |
| URL | Classroom/Office Number | Guides you to the right place |
✅ Example in Words:
-
You want to see Amina’s profile.
-
You go to URL
/students/1/→ the system (View) checks the register (Model) → finds Amina’s info → sends it to the webpage (Template) → you see her name, age, grade displayed neatly.
Week Plan: Hello Django Web Page
Goal: Students will learn to create a simple Django web page using Views, Templates, URLs, and basic project structure.
Day 1: Python & Django Setup
Objective:
-
Install Python and Django
-
Set up virtual environment
-
Create Django project
1️⃣ What is Python?
-
Python is a popular programming language.
-
It’s easy to read and write, beginner-friendly, and used in web development, data science, AI, and more.
-
Example: You can write a simple program to say hello:
2️⃣ Why Install Python?
-
Python is required to run Django, because Django is built on Python.
-
It allows you to write and execute Python code on your computer.
-
You cannot use Django without Python installed.
3️⃣ How to Install Python
Step 1: Download Python
-
Click Download Python 3.x (latest version)
Step 2: Install Python
-
Windows: Run the installer and check the box “Add Python to PATH”
✅ This allows your computer to find Python from the terminal. -
Mac/Linux: Python usually comes pre-installed. If not, use Homebrew (Mac) or apt (Linux).
Step 3: Verify Installation
Open your terminal (cmd on Windows, Terminal on Mac/Linux) and type:
Explanation:
-
python→ command to run Python -
--version→ asks Python to show the version installed
✅ You should see something like: Python 3.12.0
4️⃣ What is Django?
-
Django is a Python framework for building websites.
-
It provides a ready-made structure (like a blueprint) to build web applications quickly.
-
With Django, you can make websites, blogs, e-commerce stores, and more without writing everything from scratch.
5️⃣ Why Install Django?
-
Django simplifies web development by handling:
-
Routing (URLs to views)
-
Database interactions
-
Templates (HTML)
-
User authentication
-
-
You don’t need to write all these from scratch.
6️⃣ How to Install Django
Step 1: Create a Virtual Environment (Recommended)
Explanation:
-
python -m venv→ tells Python to make a virtual environment (isolated workspace) -
myenv→ the name of your environment
✅ A virtual environment keeps your project isolated from other Python projects.
Step 2: Activate the Virtual Environment
-
Windows:
-
Mac/Linux:
Explanation:
-
Activating the environment makes Python use packages installed only inside this project.
-
You’ll see
(myenv)at the start of the terminal line after activation.
Step 3: Install Django
Explanation:
-
pip→ Python’s package manager (like App Store for Python tools) -
install django→ tells pip to download and install Django in the current virtual environment
Step 4: Verify Django Installation
Explanation:
-
django-admin→ command-line tool for Django -
--version→ shows the installed version
✅ You should see something like: 4.2.0
This means Django is ready to use!
7️⃣ Classwork Example
-
Open terminal
-
Create virtual environment:
-
Activate it:
-
Windows:
-
Mac/Linux:
-
Install Django:
-
Verify:
8️⃣ Assignment
-
Write 2 sentences explaining:
-
Why Python is needed for Django
-
Why we use a virtual environment
-
-
Screenshot the terminal showing Python and Django versions.
Classwork:
-
Check Python installation:
python --version -
Create a virtual environment:
python -m venv myenv -
Activate virtual environment and install Django:
pip install django -
Verify Django:
django-admin --version
Assignment:
-
Write 2–3 sentences explaining why we use virtual environments.
-
Create a folder called
my_first_djangofor the project.
Day 2: Creating App & View
Objective:
-
Create a Django app
-
Understand Views and how they handle logic
Step-by-Step: Create Django App & Understand Views
1️⃣ What is a Django App?
-
A Django Project is the entire website.
-
An App is a module inside the project that handles a specific feature.
-
Example:
blog,shop,helloapp
-
-
You can have multiple apps in one project.
Why Apps?
-
Organizes code
-
Makes it reusable
-
Easier to maintain
2️⃣ Create a Django Project (If not done yet)
django-admin startproject helloproject
cd helloproject
Explanation:
-
startproject helloproject→ creates a new Django project folder calledhelloproject -
cd helloproject→ moves into that folder
3️⃣ Create a Django App
python manage.py startapp helloapp
Explanation:
-
python manage.py→ tells Python to run Django’s command tool -
startapp helloapp→ creates a new app calledhelloapp
Folder structure created:
helloapp/
__init__.py
admin.py
apps.py
models.py
tests.py
views.py
migrations/
-
views.py→ where we write the logic to control what the user sees -
models.py→ where we handle data (database)
4️⃣ Register App in Project
Open helloproject/settings.py → find INSTALLED_APPS → add 'helloapp',:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'helloapp', # Registering our app
]
Explanation:
-
Django needs to know about our app to include it in the project
-
This allows Django to manage URLs, templates, and models in
helloapp
5️⃣ Create a View (Logic)
Open helloapp/views.py and add:
from django.shortcuts import render
def home(request):
return render(request, 'hello.html')
Line-by-line explanation:
-
from django.shortcuts import render-
Imports
render, a function that connects views to templates (HTML pages)
-
-
def home(request):-
Creates a function-based view called
home -
requestis information sent by the browser
-
-
return render(request, 'hello.html')-
Tells Django to show the template
hello.html -
renderautomatically looks for templates inside the app’stemplatesfolder
-
6️⃣ Create Template (HTML Page)
-
Inside
helloapp/, create foldertemplates -
Inside
templates/, create filehello.html:
<!DOCTYPE html>
<html>
<head>
<title>Hello Page</title>
</head>
<body>
<h1>Hello, Django World!</h1>
</body>
</html>
Explanation:
-
HTML defines what the user sees
-
h1is a heading displayed on the page
7️⃣ Connect URL to View
(a) Create helloapp/urls.py (new file)
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
]
Explanation:
-
path('', views.home)→ when user visits root URL, showhomeview -
name='home'→ optional name for referencing in templates
(b) Include App URLs in Project → helloproject/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('helloapp.urls')), # Include app URLs
]
Explanation:
-
include('helloapp.urls')→ tells Django to look intohelloapp/urls.pyfor routing
8️⃣ Run Server and Test
python manage.py runserver
-
Open browser: http://127.0.0.1:8000/
-
You should see: Hello, Django World!
9️⃣ Classwork (Student-Centered)
-
Change
<h1>text to “Hello, [Your Name]!” -
Add another view called
aboutand createabout.html
10️⃣ Assignment
-
Create 2 more pages:
contactandservices -
Each page should have a different message and heading
-
Update
urls.pyto include these pages
Do you want me to do that next?
Classwork:
-
Create app:
python manage.py startapp helloapp -
Register app in
settings.py(INSTALLED_APPS) -
Create a view in
helloapp/views.py:
from django.shortcuts import render
def home(request):
return render(request, 'hello.html')
Assignment:
-
Create another view called
aboutthat will return a templateabout.html.
Day 3: Templates & URLs
Objective:
-
Understand Templates and HTML
-
Connect URLs to views
Perfect! Let’s do a student-friendly guide on Templates and HTML and connecting URLs to Views in Django, explaining what, why, and how with every line of code.
Django Templates & URLs: Beginner-Friendly Guide
1️⃣ What is a Template?
-
A Template is an HTML file that defines what the user sees on the web page.
-
In Django, Templates are connected to Views.
-
Templates can include text, images, links, and dynamic content.
Why use templates?
-
Separates design (HTML) from logic (Views)
-
Makes your website easier to maintain and update
2️⃣ What is a URL in Django?
-
A URL is the web address the user visits in the browser.
-
In Django, URLs are connected to Views which then decide what page to show.
Example:
-
http://127.0.0.1:8000/→ homepage -
http://127.0.0.1:8000/about/→ about page
3️⃣ Step 1: Create Template Folder
Inside your app (helloapp/), create a folder called templates.
Folder structure:
helloapp/
templates/
hello.html
about.html
4️⃣ Step 2: Create HTML Templates
home page template: hello.html
<!DOCTYPE html>
<html>
<head>
<title>Hello Page</title>
</head>
<body>
<h1 style="color: green; text-align:center;">Hello, Django World!</h1>
</body>
</html>
Explanation:
-
<html>→ starts HTML page -
<head>→ contains meta info, title, CSS links -
<title>→ shows in browser tab -
<body>→ visible content -
<h1>→ heading text shown on page
about page template: about.html
<!DOCTYPE html>
<html>
<head>
<title>About Page</title>
</head>
<body>
<h1 style="color: blue; text-align:center;">About This Django App</h1>
<p>This app demonstrates Django Templates and URLs.</p>
</body>
</html>
Explanation:
-
<p>→ paragraph text -
This template will be shown when users visit
/about/
5️⃣ Step 3: Update Views
Open helloapp/views.py and add:
from django.shortcuts import render
def home(request):
return render(request, 'hello.html')
def about(request):
return render(request, 'about.html')
Line-by-line explanation:
-
def home(request)→ function for homepage -
render(request, 'hello.html')→ tells Django to showhello.html -
def about(request)→ function for about page -
render(request, 'about.html')→ tells Django to showabout.html
6️⃣ Step 4: Connect URLs to Views
(a) App-level URLs: helloapp/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'), # Homepage
path('about/', views.about, name='about'), # About page
]
Explanation:
-
path('', views.home)→ root URL showshomeview -
path('about/', views.about)→/about/showsaboutview
(b) Project-level URLs: helloproject/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('helloapp.urls')), # Include app URLs
]
Explanation:
-
include('helloapp.urls')→ Django looks inhelloapp/urls.pyfor routing -
admin/→ default Django admin page
7️⃣ Step 5: Run Server
python manage.py runserver
-
Open browser: http://127.0.0.1:8000/ → homepage
-
Open browser: http://127.0.0.1:8000/about/ → about page
✅ You should see different content for each page.
8️⃣ Classwork (Student-Centered)
-
Change
<h1>colors on both pages -
Add a new page
contactwith message: “Contact us at contact@example.com” -
Update
views.pyandurls.pyfor/contact/page -
Test in browser
9️⃣ Assignment
-
Create another page called
services -
Add a paragraph describing services
-
Update URLs and Views
-
Test all pages in browser
10️⃣ Summary
| Component | Role |
|---|---|
| Template | HTML design (what user sees) |
| View | Logic (what template to show) |
| URL | Connects browser address to view |
Classwork:
-
Create folder
helloapp/templates -
Create
hello.htmlwith:
<h1 style="color: green; text-align:center;">Hello, Django World!</h1>
-
Create
urls.pyin the app:
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
path('about/', views.about, name='about'),
]
-
Include app URLs in
helloproject/urls.py:
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('helloapp.urls')),
]
Assignment:
-
Change the color and text of
<h1>inhello.html -
Test
/aboutpage in browser
Day 4 (Friday): Mini Project
Objective:
-
Apply all learned concepts in a small project
Project: “Student Greeting Page”
Tasks for Students:
-
Modify
homeview to accept a name from the URL (usepath('hello/<str:name>/')) -
Display “Hello, [name]! Welcome to Django” in template
-
Add a new template
about.htmlthat describes the app -
Test both pages in the browser
Example: views.py
from django.shortcuts import render
def home(request, name):
return render(request, 'hello.html', {'name': name})
def about(request):
return render(request, 'about.html')
Example: hello.html
<h1>Hello, {{ name }}! Welcome to Django</h1>
Example: urls.py
urlpatterns = [
path('hello/<str:name>/', views.home, name='home'),
path('about/', views.about, name='about'),
]
Class Activity:
-
Each student tests their own name
-
Change colors, font size, and add styles
Reflection:
-
“What did I learn about Views, Templates, and URLs?”
-
“Which part was most exciting?”
Models
-
What: Python class that represents a database table.
-
Why: Avoid SQL, organize data, work with forms and admin.
-
Learn before: Python classes, field types, database basics, migrations.
Day 1: Introduction to Django Models (Simple Version)
Learning Goal for Today:
-
Understand what a Django model is
-
Learn the parts of a model (class, fields)
-
Create a simple model with one table
1. Teacher Explanation
What is a Model?
-
Think of a model as a box that holds information.
-
Each thing you store in the box is called a field.
-
Example: Student box → name, age, grade
Why Models Are Important:
-
They create database tables automatically.
-
You can save, update, and read data easily using Python.
Components of a Model (Simple):
| Component | What it Means |
|---|---|
| Class Name | Name of the box/table (Student) |
| Fields | Things inside the box (name, age, grade) |
| Methods (Optional) | Actions the box can do (like check if a student is passing) |
2. Simple Code Example
from django.db import models
# This is our first box (table)
class Student(models.Model):
name = models.CharField(max_length=100) # A text field for student name
age = models.IntegerField() # A number field for student age
grade = models.CharField(max_length=2) # A text field for grade, e.g., "A", "B"
# Optional method to check if student is passing
def is_passing(self):
return self.grade in ['A', 'B', 'C']
Explanation for Students:
-
·
from django.db import models→ Brings in tools needed to make models.· Parameters: None
·
class Student(models.Model):→ Creates a table called Student.· Parameters:
models.Model→ Inherits database model behavior, enabling Django to treat it as a table.·
name = models.CharField(max_length=100)→ Text field for student name.· Parameters:
max_length=100→ Maximum number of characters allowed in the field.·
age = models.IntegerField()→ Number field for student age.· Parameters: Optional parameters include
default,null,blank(e.g.,age = models.IntegerField(default=0)).·
grade = models.CharField(max_length=2)→ Text field for grade (like "A").· Parameters:
max_length=2→ Maximum of 2 characters allowed. Optional parameters:default,choices,null,blank.·
def is_passing(self):→ Function inside the model to check if the student is passing.· Parameters:
self→ Refers to the current student object.·
return self.grade in ['A', 'B', 'C']→ Returns True if grade is A, B, or C; otherwise False.· Parameters:
self.grade→ Accesses the grade of the current student object;['A', 'B', 'C']→ List of passing grades.
3. Student Activities (Hands-On)
-
Draw the Box:
+------------------+ | Student Box | |------------------| | name | | age | | grade | +------------------+ -
Type the Code:
-
Open
models.pyin your Django app -
Copy the Student model above
-
Think and Discuss:
-
Ask: “What grade is passing?”
-
Ask: “What other fields can we add? Email? Attendance?”
4. Mini Task / Assignment
Task: Create a simple Book box (model)
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.CharField(max_length=100)
year = models.IntegerField()
-
Draw a diagram of your Book box.
-
Optional: Add a method to check if the book is new (published after 2020):
def is_new(self):
return self.year > 2020
5. Key Points to Remember
-
A model = a Python class = a table in the database
-
Fields = columns in the table
-
Methods = actions the table can do
-
Use simple field types:
CharField(text),IntegerField(numbers)
✅ Outcome for Day 1:
-
Students can explain what a model is
-
Students can write a simple model with 2–3 fields
-
Students can draw a diagram showing the model and its fields
Perfect! Let’s focus on Day 2: Creating and Migrating Models in Django. I’ll break it down line by line, step by step, with teacher and student activities, and beginner-friendly explanations.
Day 2: Creating and Migrating Models
Topic: Turning Django Models into Database Tables
Learning Goal for Today:
By the end of the day, students should be able to:
-
Understand what migrations are
-
Create database tables from models
-
Add records (rows) to tables
-
See the data in Django shell
1. Teacher Explanation
What is a Migration?
-
Analogy: “You made a box on paper (your model). Now you need to put it on a real shelf (database). Migrations do that for you.”
-
Migrations tell Django:
-
“I have a new table”
-
“I added/removed a field”
-
“Update the database structure”
-
Key Commands for Migrations
| Command | Purpose |
|---|---|
python manage.py makemigrations |
Create migration files based on your models |
python manage.py migrate |
Apply migrations to the database and create tables |
Why Use Django Shell?
-
Shell is like a playground for your models
-
You can create, update, delete, and query data using Python
2. Step-by-Step Demonstration
Example: Using the Student model from Day 1
Step 1: Make Migrations
python manage.py makemigrations
Explanation:
-
Django looks at your models and prepares instructions to create database tables.
Step 2: Apply Migrations
python manage.py migrate
Explanation:
-
Django runs the instructions and creates the tables in your database.
Step 3: Open Django Shell
python manage.py shell
Explanation:
-
Opens an interactive Python shell to play with your models.
Step 4: Create Records
from myapp.models import Student # Import the Student model
s1 = Student(name="Alice", age=15, grade="A") # Create a Student object
s1.save() # Save it to the database
# Or in one line
Student.objects.create(name="Bob", age=16, grade="B")
Step 5: Check Records
Student.objects.all() # Shows all students in the database
3. Student Activities (Hands-On)
-
Teacher Demo: Run
makemigrationsandmigratein terminal -
Students Try:
-
Run the commands themselves
-
Open Django shell and create 2 students
-
Use
Student.objects.all()to see their records
-
-
Discussion:
-
“What happens if you forget to run
migrate?” → Tables won’t exist, and data cannot be saved. -
“Why do we need
makemigrationsbeforemigrate?” →makemigrationscreates the instructions;migrateexecutes them
-
4. Mini Task / Assignment
Task 1: Create a Teacher model:
from django.db import models
class Teacher(models.Model):
name = models.CharField(max_length=100)
subject = models.CharField(max_length=50)
-
Make migrations and migrate the model
-
Add 2 teachers using Django shell
-
Check all records using
Teacher.objects.all()
Task 2 (Optional Advanced):
-
Create a
Bookmodel from Day 1 -
Add 3 books and display them in Django shell
5. Key Points to Remember
-
Models = blueprint for tables
-
makemigrations → Creates instructions for changes
-
migrate → Applies instructions to the database
-
shell → Safe playground to interact with models
-
save() → Saves a model instance to the database
-
objects.create() → Shortcut to create and save in one step
✅ Outcome for Day 2:
By the end of the day, students can:
-
Run migrations to create tables from models
-
Add, view, and check records using Django shell
-
Explain the purpose of
makemigrationsandmigrate
Perfect! Since you’re using VS Code, we can adapt Day 3 activities to it, step by step, so everything works inside VS Code. I’ll explain exactly what to do.
Day 3: Querying and Updating Models (Django ORM) in VS Code
1. Open Your Django Project in VS Code
-
Open VS Code.
-
Go to File → Open Folder → Select your Django project folder.
-
Make sure your terminal is open in VS Code (View → Terminal).
2. Open Django Shell in VS Code Terminal
python manage.py shell
-
This opens the interactive Python shell inside your project.
-
You can now play with your models directly.
3. Import Your Models
from myapp.models import Student
-
Replace
myappwith your app’s name. -
This makes the Student model available in the shell.
4. Query Records
Get all students:
Student.objects.all()
Filter students with grade A:
Student.objects.filter(grade="A")
Get a specific student by ID:
s1 = Student.objects.get(id=1)
-
s1is now a single student object you can update or delete.
5. Update Records
s1.grade = "B" # Change the grade
s1.save() # Save changes to the database
-
Always call
.save()after changing a field to update the database.
6. Delete Records
s1.delete() # Deletes this student from the database
-
This removes the record completely.
7. Practice in VS Code Terminal
-
Retrieve all students:
Student.objects.all() -
Filter by grade:
Student.objects.filter(grade="A") -
Pick a student:
s1 = Student.objects.get(id=1) -
Update the student:
s1.grade = "B"; s1.save() -
Delete a student:
s1.delete()
-
Watch the output after each command in the VS Code terminal.
8. Mini Task / Assignment (VS Code)
Task 1:
-
Use the
Teachermodel from Day 2:-
Retrieve all teachers
-
Filter teachers by subject
-
Update a teacher’s subject
-
Delete a teacher record
-
Task 2 (Optional Advanced):
-
Use the
Bookmodel from Day 1:-
Filter books published after 2020
-
Update a book title
-
Delete a book record
-
9. Key Points for VS Code Users
-
You can do everything in VS Code terminal.
-
Always run
python manage.py shellto test queries. -
Use autocomplete in VS Code (press
Tab) to explore methods like.all(),.filter(),.save(). -
Remember: .save() = update database; .delete() = remove record
✅ Outcome in VS Code:
-
Students can query, filter, update, and delete records using Django ORM in VS Code.
-
They can see live results immediately in the terminal.
Perfect! Let’s focus on Day 4: Relationships Between Models and Methods in Django. I’ll break it down step by step, line by line, with teacher and student activities, beginner-friendly explanations, and simple code examples.
Day 4: Relationships Between Models and Methods (Django)
Topic: Connecting Models and Adding Methods
Learning Goal for Today:
By the end of the day, students should be able to:
-
Understand relationships between models (One-to-One, One-to-Many, Many-to-Many)
-
Create related models in Django
-
Write methods inside models to perform tasks
-
Use Django shell to test relationships and methods
1. Teacher Explanation
1.1 Why Relationships?
-
Analogy:
-
“A student belongs to a class, and a class has many students. A teacher teaches many classes.”
-
-
Relationships allow us to link models and organize data better.
1.2 Types of Relationships
| Relationship | Django Field | Example |
|---|---|---|
| One-to-One | OneToOneField |
Each student has one unique profile |
| One-to-Many | ForeignKey |
One teacher teaches many students |
| Many-to-Many | ManyToManyField |
A student can enroll in many courses, and a course has many students |
1.3 Methods in Models
-
Methods are functions inside a model that perform actions on that model.
-
Examples:
-
def is_passing(self)→ Checks if a student’s grade is passing -
def full_name(self)→ Returns full name of a teacher
-
2. Step-by-Step Code Example
Step 1: Create Related Models
from django.db import models
# Teacher model
class Teacher(models.Model):
name = models.CharField(max_length=100)
subject = models.CharField(max_length=50)
# Student model with relationship to Teacher
class Student(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
grade = models.CharField(max_length=2)
teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE) # One teacher → Many students
# Method to check if student is passing
def is_passing(self):
return self.grade in ['A', 'B', 'C']
Step 2: Explain Line by Line
-
teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE)-
Creates a One-to-Many relationship: One teacher teaches many students.
-
on_delete=models.CASCADE→ If the teacher is deleted, all their students are deleted too.
-
-
def is_passing(self):-
Method to check if student’s grade is A, B, or C.
-
3. Student Activities (Hands-On)
-
Make Migrations and Migrate
python manage.py makemigrations
python manage.py migrate
-
Test Relationships in Django Shell
from myapp.models import Teacher, Student
# Create a teacher
t1 = Teacher.objects.create(name="Mr. John", subject="Math")
# Create students for this teacher
s1 = Student.objects.create(name="Alice", age=15, grade="A", teacher=t1)
s2 = Student.objects.create(name="Bob", age=16, grade="B", teacher=t1)
# Check teacher of a student
s1.teacher.name # Output: "Mr. John"
# Get all students of a teacher
t1.student_set.all() # Returns a queryset of students
-
Test Methods
s1.is_passing() # Returns True
s2.is_passing() # Returns True
4. Mini Task / Assignment
Task 1:
-
Create a
Coursemodel with fields:title,description -
Create a Many-to-Many relationship with
Student -
Add 2 courses and assign multiple students to each course
Task 2 (Optional Advanced):
-
Add a method
student_count(self)in Teacher model that returns number of students taught by that teacher:
def student_count(self):
return self.student_set.count()
5. Key Points to Remember
-
Relationships help link models logically
-
ForeignKey→ One-to-Many -
OneToOneField→ One-to-One -
ManyToManyField→ Many-to-Many -
Methods inside models perform tasks and return information
-
Always test relationships and methods in Django shell
✅ Outcome for Day 4:
By the end of the day, students can:
-
Create related models using One-to-One, One-to-Many, Many-to-Many
-
Write methods inside models to check or calculate information
-
Retrieve related objects in Django shell
-
Understand how models, relationships, and methods work together
Perfect! Let’s plan Friday: Mini Project – School Management System in a step-by-step, beginner-friendly way, using everything learned from Days 1–4. I’ll include teacher activities, student activities, and a full guide with code examples.
Friday: Mini Project – School Management System
Project Goal:
-
Build a simple School Management System in Django using models, relationships, and methods learned earlier.
-
Students will create models, add relationships, test data, and write methods.
1. Teacher Explanation
Project Overview:
-
Models:
Teacher,Student,Course -
Relationships:
-
One teacher → Many students (ForeignKey)
-
Many students ↔ Many courses (ManyToManyField)
-
-
Methods:
-
is_passing()→ Check if student is passing -
student_count()→ Number of students a teacher teaches
-
Steps for Students:
-
Create models
-
Make and apply migrations
-
Add sample data in Django shell
-
Query and update data
-
Test methods
2. Step-by-Step Code Example
Step 1: Create Models (models.py)
from django.db import models
# Teacher model
class Teacher(models.Model):
name = models.CharField(max_length=100)
subject = models.CharField(max_length=50)
# Method to count students
def student_count(self):
return self.student_set.count()
# Course model
class Course(models.Model):
title = models.CharField(max_length=100)
description = models.TextField()
# Student model
class Student(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
grade = models.CharField(max_length=2)
teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE) # One-to-Many
courses = models.ManyToManyField(Course) # Many-to-Many
# Method to check if student is passing
def is_passing(self):
return self.grade in ['A', 'B', 'C']
Step 2: Make Migrations and Migrate
python manage.py makemigrations
python manage.py migrate
-
Creates database tables for
Teacher,Student, andCourse.
Step 3: Add Sample Data (Django Shell)
from myapp.models import Teacher, Student, Course
# Create teachers
t1 = Teacher.objects.create(name="Mr. John", subject="Math")
t2 = Teacher.objects.create(name="Mrs. Mary", subject="English")
# Create courses
c1 = Course.objects.create(title="Algebra", description="Basic Algebra course")
c2 = Course.objects.create(title="Grammar", description="English Grammar course")
# Create students
s1 = Student.objects.create(name="Alice", age=15, grade="A", teacher=t1)
s2 = Student.objects.create(name="Bob", age=16, grade="B", teacher=t1)
s3 = Student.objects.create(name="Charlie", age=14, grade="D", teacher=t2)
# Assign students to courses
s1.courses.add(c1)
s2.courses.add(c1, c2)
s3.courses.add(c2)
Step 4: Query and Test Methods
# Check students of Mr. John
t1.student_set.all() # Returns [Alice, Bob]
# Check if students are passing
s1.is_passing() # True
s3.is_passing() # False
# Check courses for Bob
s2.courses.all() # Returns [Algebra, Grammar]
# Count students for a teacher
t1.student_count() # 2
3. Student Activities (Hands-On)
-
Create models (
Teacher,Student,Course) with relationships -
Make migrations and migrate to create tables
-
Add sample data in Django shell
-
Test queries: filter students, check passing status, list courses
-
Update and delete records as needed
4. Mini Tasks / Assignment
-
Add another method in Student model to return full info:
def full_info(self):
return f"{self.name}, Age: {self.age}, Grade: {self.grade}, Teacher: {self.teacher.name}"
-
Add another method in Course to list all students in that course:
def students_enrolled(self):
return self.student_set.all()
-
Bonus: Add more students, teachers, and courses, and experiment with queries.
5. Key Points to Remember
-
Models define tables
-
Relationships (
ForeignKey,ManyToManyField) connect tables -
Methods in models perform actions on data
-
Django shell is your testing playground
✅ Outcome for Friday Project:
-
Students can build a mini School Management System
-
Understand models, relationships, and methods
-
Can add, update, query, and delete data using Django ORM
Views
-
What: Python function or class that decides what data to show.
-
Why: Connect models (data) to templates (HTML), make app dynamic.
-
Learn before: Python functions/classes, models, templates, URLs.
Absolutely! Let’s make a student-centered teaching note for Introduction to Django Views, complete with what it is, why, where, components, examples, exercises with solutions, and assignment. This is structured so you can teach directly without thinking.
π️ Day 1: Introduction to Django Views
Topic: Introduction to Django Views
Level: Beginner / Student-Centered Learning
Tools: VS Code, Python, Django installed
1. Lesson Objectives
By the end of this lesson, students should be able to:
-
Explain what a View is in Django.
-
Describe why Django Views are needed.
-
Identify the components of a Django View.
-
Create a simple Django View and link it to a URL.
2. What is a Django View?
A View is the brain or decision-maker in a Django application.
-
It receives user requests (like visiting a webpage).
-
Processes the request (can fetch data from database, check logic).
-
Returns a response (text, HTML page, or JSON).
π Nigerian Analogy:
Imagine a restaurant:
-
You (user) place an order.
-
The waiter (View) checks what you want, goes to the kitchen (Model) and brings your food (Response).
Without the waiter (View), you wouldn’t get your meal.
3. Why We Need Django Views
-
Control Responses – Decide what the user sees on each page.
-
Process Requests – Handle form submissions, URL actions, or clicks.
-
Connect Templates & Data – Show HTML pages with dynamic content.
-
Separate Logic – Keeps code organized; View handles logic, Templates handle presentation.
4. Where Views Are Used
Views are used everywhere in a Django app whenever you want to:
-
Display a webpage (Homepage, About, Services).
-
Show database data (List of students, products).
-
Handle forms (Contact forms, login forms).
-
Return JSON data (APIs).
5. Components of a Django View
| Component | Description | Example |
|---|---|---|
| Function or Class | The core piece that receives requests | def home(request) or class HomeView(View) |
| Request Object | Automatically passed; contains info about the user request | request.method shows GET/POST |
| Response Object | What you send back to the user | HttpResponse("Hello") |
| Template (Optional) | HTML page to render content nicely | render(request, 'home.html', context) |
| Context (Optional) | Data passed to template | context = {'name':'Amina'} |
6. Simple Example: Function-Based View
Step 1: Create a view
# views.py
from django.http import HttpResponse
def home(request):
return HttpResponse("Welcome to Nobigdeal Training Centre")
Step 2: Connect view to URL
# urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
]
✅ Result: Visiting http://127.0.0.1:8000/ shows:
“Welcome to Nobigdeal Training Centre”
7. Simple Class-Based View Example
# views.py
from django.http import HttpResponse
from django.views import View
class HomeView(View):
def get(self, request):
return HttpResponse("Welcome to Nobigdeal Training Centre (Class-Based)")
URL Mapping:
from django.urls import path
from .views import HomeView
urlpatterns = [
path('', HomeView.as_view(), name='home'),
]
✅ .as_view() converts the class into a callable view.
8. Exercises (Classwork)
-
Create a Function-Based View called
aboutthat displays:
“This is Nobigdeal ICT Training Centre in Kubwa, Abuja.”
Connect it to/about/URL. -
Create a Class-Based View called
servicesthat displays:
“Services: Training, Printing, Online Registration”
Connect it to/services/URL.
9. Solutions to Exercises
Function-Based View:
def about(request):
return HttpResponse("This is Nobigdeal ICT Training Centre in Kubwa, Abuja")
Class-Based View:
class ServicesView(View):
def get(self, request):
return HttpResponse("Services: Training, Printing, Online Registration")
URLs:
urlpatterns = [
path('about/', views.about, name='about'),
path('services/', ServicesView.as_view(), name='services'),
]
10. Homework / Assignment
-
Create a view
contactthat displays:
“Call us at 0803-000-0000 or email: nobigdeal@gmail.com”
Connect it to/contact/. -
Optional: Create a GalleryView (Class-Based) showing:
“See photos from our previous training sessions.”
11. Summary Table for Students
| Term | Meaning (Nigeria Example) | Example |
|---|---|---|
| View | Decision-maker of a page | home(request) |
| Request | User input or page visit | request.method |
| Response | What user sees | HttpResponse("Hello") |
| Function-Based View | Simple function handling request | def home(request): ... |
| Class-Based View | Class handling request | class HomeView(View) |
| Template | HTML page to render content | home.html |
| Context | Data passed to template | {'name': 'Amina'} |
✅ Teacher Tip:
-
Use Nigerian-friendly examples (Nobigdeal Training Centre, Kubwa, Danfo, Market).
-
Show both FBV and CBV side by side to explain differences.
-
Emphasize
.as_view()for class-based views.
Perfect! Let’s create a student-centered teaching note for Function-Based Views (FBV) in Django, fully detailed with what it is, why, components, examples, exercises with solutions, and assignment.
π️ Day 2: Function-Based Views (FBV)
Topic: Function-Based Views in Django
Level: Beginner / Student-Centered Learning
Tools: VS Code, Python, Django installed
1. Lesson Objectives
By the end of this lesson, students should be able to:
-
Explain what a Function-Based View (FBV) is.
-
Create and use FBVs in a Django project.
-
Connect FBVs to URLs.
-
Display simple text and dynamic content using FBVs.
2. What is a Function-Based View (FBV)?
A Function-Based View is a normal Python function that receives a request and returns a response.
π Analogy (Nigeria Example):
Think of an FBV as a waiter in a restaurant:
-
A customer (user) comes in.
-
The waiter (FBV function) receives the request, checks what the customer wants, and brings the food (response).
3. Why We Use FBVs
-
Simple and Easy – Great for small projects and beginners.
-
Organized Code – Keeps logic for each page in its own function.
-
Quick to Test – Easy to run and see results in the browser.
4. Components of a Function-Based View
| Component | Description | Example |
|---|---|---|
| Function | The Python function that handles a request | def home(request): |
| Request Object | Automatically passed; contains info about the user request | request.method |
| Response Object | What is returned to the user | HttpResponse("Hello World") |
| Context (Optional) | Data passed to a template | context = {'name': 'Amina'} |
| Template (Optional) | HTML page for display | render(request, 'home.html', context) |
5. Basic Example of FBV
views.py
from django.http import HttpResponse
def home(request):
return HttpResponse("Welcome to Nobigdeal Training Centre")
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
]
✅ Result:
Visiting http://127.0.0.1:8000/ displays:
“Welcome to Nobigdeal Training Centre”
6. FBV with Multiple Pages
views.py
def about(request):
return HttpResponse("We train students in ICT, Graphics, and Coding.")
def services(request):
return HttpResponse("Our services: Training, Printing, Online Registration")
urls.py
urlpatterns = [
path('about/', views.about, name='about'),
path('services/', views.services, name='services'),
]
✅ Result:
-
/about/→ About page -
/services/→ Services page
7. FBV with Template and Context
views.py
from django.shortcuts import render
def home(request):
context = {'title': 'Welcome', 'centre': 'Nobigdeal Training Centre'}
return render(request, 'home.html', context)
home.html
<!DOCTYPE html>
<html>
<head>
<title>{{ title }}</title>
</head>
<body>
<h1>{{ centre }}</h1>
</body>
</html>
✅ Result:
Displays nicely formatted HTML page with dynamic content.
8. Classwork / Exercises
-
Create a Function-Based View
contactthat displays:
“Call us at 0803-000-0000 or email nobigdeal@gmail.com”
Connect it to/contact/. -
Create another FBV
gallerythat displays:
“Check our previous training session photos.” -
Bonus: Add a context dictionary to
homepage to show a dynamic welcome message like:
“Welcome, [Your Name] to Nobigdeal Training Centre!”
9. Solutions / Example Code
views.py
def contact(request):
return HttpResponse("Call us at 0803-000-0000 or email nobigdeal@gmail.com")
def gallery(request):
return HttpResponse("Check our previous training session photos.")
urls.py
urlpatterns = [
path('contact/', views.contact, name='contact'),
path('gallery/', views.gallery, name='gallery'),
]
FBV with Context Example
def home(request):
context = {'message': 'Welcome, Amina, to Nobigdeal Training Centre!'}
return render(request, 'home.html', context)
home.html
<h1>{{ message }}</h1>
10. Homework / Assignment
-
Create a Function-Based View called
aboutthat displays:
“Nobigdeal Training Centre is the best ICT training centre in Abuja.” -
Create a page
/services/showing 3 services:-
ICT Training
-
Graphic Design
-
Online Registration
-
-
Optional: Use context dictionary to pass your name dynamically to a template.
11. Summary Table
| Term | Meaning (Nigeria Example) | Example |
|---|---|---|
| Function-Based View (FBV) | A Python function handling requests | def home(request) |
| Request | User input or visit | request.method |
| Response | What user sees | HttpResponse("Hello") |
| Template | HTML page | home.html |
| Context | Data passed to template | {'name': 'Amina'} |
✅ Teacher Tip:
-
Show FBVs first before moving to Class-Based Views (CBVs).
-
Emphasize connecting views to URLs.
-
Encourage students to test each page in browser.
Perfect! Let’s create a student-centered teaching note for Class-Based Views (CBV) in Django, fully detailed with what it is, why, components, examples, classwork, exercises with solutions, and assignment.
π️ Day 3: Class-Based Views (CBV)
Topic: Class-Based Views in Django
Level: Beginner / Student-Centered Learning
Tools: VS Code, Python, Django installed
1. Lesson Objectives
By the end of this lesson, students should be able to:
-
Explain what a Class-Based View (CBV) is.
-
Create and use CBVs in a Django project.
-
Understand the
.as_view()method. -
Compare CBVs with Function-Based Views (FBV).
2. What is a Class-Based View (CBV)?
A Class-Based View uses a Python class instead of a function to handle requests.
π Nigerian Analogy:
Think of CBV as a restaurant supervisor:
-
The customer (user) comes in.
-
The supervisor (CBV class) has multiple staff (methods) for different tasks.
-
The supervisor can delegate tasks like serving food, cleaning, or taking orders (GET, POST requests).
3. Why Use CBVs
-
Organized Code – Methods inside a class group related logic together.
-
Reusable – Can inherit logic from other CBVs for similar pages.
-
Handles Multiple Request Types – Separate methods for GET, POST, PUT, DELETE.
-
Good for Large Projects – Neater and easier to maintain than many FBVs.
4. Components of a CBV
| Component | Description | Example |
|---|---|---|
| Class | Python class representing the view | class HomeView(View): |
| Methods | Functions inside the class for request types | def get(self, request): |
| Request Object | Passed automatically to methods | request.method |
| Response | Returned to the user | HttpResponse("Hello") |
| .as_view() | Converts class into a callable view | HomeView.as_view() |
| Template / Context | Optional, for rendering HTML pages | render(request, 'home.html', context) |
5. Simple CBV Example
views.py
from django.http import HttpResponse
from django.views import View
class HomeView(View):
def get(self, request):
return HttpResponse("Welcome to Nobigdeal Training Centre (Class-Based)")
urls.py
from django.urls import path
from .views import HomeView
urlpatterns = [
path('', HomeView.as_view(), name='home'),
]
✅ Result: Visiting / displays:
“Welcome to Nobigdeal Training Centre (Class-Based)”
6. CBV Handling Multiple Pages
views.py
class AboutView(View):
def get(self, request):
return HttpResponse("We train students in ICT, Graphics, and Coding.")
class ServicesView(View):
def get(self, request):
return HttpResponse("Services: Training, Printing, Online Registration")
urls.py
urlpatterns = [
path('about/', AboutView.as_view(), name='about'),
path('services/', ServicesView.as_view(), name='services'),
]
✅ Result:
-
/about/→ About page -
/services/→ Services page
7. CBV with Template and Context
views.py
from django.shortcuts import render
from django.views import View
class HomeView(View):
def get(self, request):
context = {'title': 'Welcome', 'centre': 'Nobigdeal Training Centre'}
return render(request, 'home.html', context)
home.html
<!DOCTYPE html>
<html>
<head>
<title>{{ title }}</title>
</head>
<body>
<h1>{{ centre }}</h1>
</body>
</html>
✅ Result: Displays HTML page with dynamic content using context.
8. Classwork / Exercises
-
Convert the Day 2 FBV
contactpage into a Class-Based View. -
Create a CBV
gallerythat displays:
“Check our previous training session photos.” -
Optional: Add a context dictionary to
homepage showing:
“Welcome, [Your Name] to Nobigdeal Training Centre!”
9. Solutions / Example Code
CBV Contact Page
class ContactView(View):
def get(self, request):
return HttpResponse("Call us at 0803-000-0000 or email nobigdeal@gmail.com")
CBV Gallery Page
class GalleryView(View):
def get(self, request):
return HttpResponse("Check our previous training session photos.")
URLs
urlpatterns = [
path('contact/', ContactView.as_view(), name='contact'),
path('gallery/', GalleryView.as_view(), name='gallery'),
]
CBV with Context
class HomeView(View):
def get(self, request):
context = {'message': 'Welcome, Amina, to Nobigdeal Training Centre!'}
return render(request, 'home.html', context)
home.html
<h1>{{ message }}</h1>
10. Homework / Assignment
-
Create a CBV
aboutthat displays:
“Nobigdeal Training Centre is the best ICT training centre in Abuja.” -
Create a CBV
servicespage showing 3 services:
-
ICT Training
-
Graphic Design
-
Online Registration
-
Optional: Use a context dictionary to pass your name dynamically to a template.
11. Summary Table
| Term | Meaning (Nigeria Example) | Example |
|---|---|---|
| Class-Based View (CBV) | Python class handling requests | class HomeView(View) |
| Methods | Functions inside the class for GET/POST | def get(self, request): |
| Request | User input or visit | request.method |
| Response | What user sees | HttpResponse("Hello") |
| .as_view() | Converts class into callable view | HomeView.as_view() |
| Template | HTML page | home.html |
| Context | Data passed to template | {'name': 'Amina'} |
✅ Teacher Tip:
-
Show FBV vs CBV side by side to explain differences.
-
Emphasize
.as_view()is required for CBVs. -
Encourage students to test each CBV in the browser and try adding dynamic content.
Perfect! Let’s create a student-centered teaching note for Django Views and Templates, fully detailed with what they are, why, components, examples, classwork, exercises with solutions, and assignment.
π️ Day 4: Views and Templates
Topic: Connecting Views to Templates in Django
Level: Beginner / Student-Centered Learning
Tools: VS Code, Python, Django installed
1. Lesson Objectives
By the end of this lesson, students should be able to:
-
Explain what a Template is in Django.
-
Connect Views to Templates.
-
Pass dynamic data from Views to Templates.
-
Render HTML pages with content using context dictionaries.
2. What is a Template?
A Template is an HTML file that defines how a page should look.
-
It separates presentation (HTML) from logic (Python/Django).
-
Templates use placeholders for dynamic data passed from Views.
π Nigerian Analogy:
Think of a Template as a menu card in a restaurant:
-
The card (template) shows how the dishes will appear.
-
The waiter (View) fills in the details (dynamic data) like today’s special or customer name.
3. Why Use Templates
-
Separation of Concerns – Keeps HTML separate from Python logic.
-
Reusable HTML – One template can be reused with different data.
-
Dynamic Content – Makes pages interactive using data from the database.
-
Clean and Organized Code – Easier to maintain large projects.
4. Components of Views + Templates
| Component | Description | Example |
|---|---|---|
| View | Handles the request and prepares data | def home(request): |
| Template | HTML file for rendering the page | home.html |
| Context Dictionary | Data passed from View to Template | context = {'name': 'Amina'} |
| render() function | Connects View to Template | render(request, 'home.html', context) |
| Placeholders | Where dynamic data appears in Template | {{ name }} |
5. Simple Example: Rendering a Template
Step 1: Create View
# views.py
from django.shortcuts import render
def home(request):
context = {'centre': 'Nobigdeal Training Centre', 'city': 'Abuja'}
return render(request, 'home.html', context)
Step 2: Create Template
home.html (inside templates folder)
<!DOCTYPE html>
<html>
<head>
<title>Home Page</title>
</head>
<body>
<h1>Welcome to {{ centre }}</h1>
<p>Located in {{ city }}</p>
</body>
</html>
Step 3: Connect URL
# urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
]
✅ Result:
Visiting / displays:
Welcome to Nobigdeal Training Centre
Located in Abuja
6. Passing Dynamic Data
views.py
def student_profile(request):
student = {'name': 'Amina', 'age': 12, 'grade': 'A'}
return render(request, 'profile.html', {'student': student})
profile.html
<h2>Student Profile</h2>
<p>Name: {{ student.name }}</p>
<p>Age: {{ student.age }}</p>
<p>Grade: {{ student.grade }}</p>
✅ Result:
Student Profile
Name: Amina
Age: 12
Grade: A
7. Classwork / Exercises
-
Create a View
aboutthat rendersabout.htmltemplate showing:
“We train students in ICT, Graphics, and Coding.” -
Create a View
servicespassing a list of services toservices.htmltemplate and display them using a for loop. -
Optional: Create a View
contactpassing phone and email tocontact.htmland render dynamically.
8. Solutions / Example Code
views.py
def about(request):
return render(request, 'about.html', {'centre': 'Nobigdeal Training Centre'})
def services(request):
services_list = ['ICT Training', 'Graphic Design', 'Online Registration']
return render(request, 'services.html', {'services': services_list})
def contact(request):
contact_info = {'phone': '0803-000-0000', 'email': 'nobigdeal@gmail.com'}
return render(request, 'contact.html', {'contact': contact_info})
services.html
<h1>Our Services</h1>
<ul>
{% for service in services %}
<li>{{ service }}</li>
{% endfor %}
</ul>
contact.html
<h1>Contact Us</h1>
<p>Phone: {{ contact.phone }}</p>
<p>Email: {{ contact.email }}</p>
9. Homework / Assignment
-
Create a View
galleryand templategallery.htmlthat displays 3 images of previous training sessions. -
Optional: Pass your name dynamically to the home page using context and display:
“Welcome, [Your Name], to Nobigdeal Training Centre!”
10. Summary Table
| Term | Meaning (Nigeria Example) | Example |
|---|---|---|
| Template | HTML file for display | home.html |
| Context | Data passed from View to Template | {'name': 'Amina'} |
| render() | Connects View to Template | render(request, 'home.html', context) |
| Placeholder | Where dynamic data appears in Template | {{ name }} |
| View | Handles logic and data | def home(request): |
✅ Teacher Tip:
-
Emphasize separation of logic and presentation.
-
Show dynamic content using context dictionaries.
-
Encourage students to experiment with loops and conditions in templates.
Next, we can prepare Friday Assessment / Mini Project:
-
Combine FBV, CBV, Views, and Templates
-
Example: School Management System
-
With questions and full solution
Day
5 (Friday): Weekly Assessment – Mini Project
π―
Goal
To test what students have learned
by building a small Django app.
π§Ύ
Project: Nobigdeal Web Pages
Task: Create a small Django app with the following:
- Home Page → “Welcome to Nobigdeal Training Centre.”
- About Page → “We train and empower students in ICT.”
- Services Page → List 3 services you offer.
- Contact Page → Address and email.
- All pages should be linked in urls.py and have HTML templates.
π
Assessment Questions
- What is a View in Django?
- Mention and explain two types of Views.
- What does .as_view()
do?
- Why do we connect Views to Templates?
- Write a simple def about(request)
function that returns a message.
π
Evaluation
|
Criteria |
Marks |
|
Correct Code Implementation |
20 |
|
URL Configuration |
10 |
|
Template Design |
10 |
|
Class Participation |
5 |
|
Total |
45 marks |
Day
5 (Friday): Weekly Assessment – Mini Project
π―
Goal
To test what students have learned
by building a small Django app.
π§Ύ
Project: Nobigdeal Web Pages
Task: Create a small Django app with the following:
- Home Page → “Welcome to Nobigdeal Training Centre.”
- About Page → “We train and empower students in ICT.”
- Services Page → List 3 services you offer.
- Contact Page → Address and email.
- All pages should be linked in urls.py and have HTML templates.
π
Assessment Questions
- What is a View in Django?
- Mention and explain two types of Views.
- What does .as_view()
do?
- Why do we connect Views to Templates?
- Write a simple def about(request)
function that returns a message.
π
Evaluation
|
Criteria |
Marks |
|
Correct Code Implementation |
20 |
|
URL Configuration |
10 |
|
Template Design |
10 |
|
Class Participation |
5 |
|
Total |
45 marks |
Templates
-
What: HTML file that shows data to users.
-
Why: Display data from views, keep design separate from logic, make pages dynamic.
-
Learn before: HTML & CSS, views, template syntax (
{{ }},{% %}), URLs.
Example:
<h1>Student List</h1>
<ul>
{% for student in students %}
<li>{{ student.name }} - {{ student.age }}</li>
{% endfor %}
</ul>
Perfect ✅
— let’s create a complete 1-week (Monday–Friday)
student-centered teaching note on Django Views, structured for
real classroom use.
This lesson plan uses Nigerian-friendly
examples (like Nobigdeal Training Centre) and builds gradually from theory
to practical and project assessment.
π️ WEEKLY
TOPIC: DJANGO VIEWS
Duration: 5 Days (Monday – Friday)
Focus: Understanding, creating, and using Django Views to handle user
requests.
π§ General Learning Goal
By the end of the week, students
should be able to:
- Explain what Views are and their importance.
- Create Function-Based and Class-Based Views.
- Connect Views with URLs and Templates.
- Build a mini web app using Views.
π️ Day 1 (Monday):
Introduction to Django Views
π― Lesson Objectives
Students should be able to:
- Explain what a View is in Django.
- Describe why Views are needed.
- Understand the types of Views in Django.
π§© 1. Introduction
In Django, a View is what
decides what the user sees when they visit your website.
It connects what users do (request) with what they get (response).
πAnalogy (Nigeria
Example):
Imagine you enter Nobigdeal Restaurant and order rice.
- You (user) make a request.
- The waiter (View) goes to the kitchen, collects
your food (Model data), and brings it to you (Response).
Without the waiter (View), you can’t
get what you want.
π‘ 2. Why We Need Views
- To control what happens when a page loads.
- To display information from the database.
- To receive and process form input.
π§± 3. Types of Views
Type
Meaning
Example
Use
Function-Based View (FBV)
A normal function that handles a
request.
Small apps
Class-Based View (CBV)
A class that handles requests more
neatly.
Big projects
π§Ύ Example (Simple
Function-Based View)
views.py
from django.http import HttpResponse
def home(request):
return HttpResponse("Welcome to Nobigdeal Training Centre")
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
]
✅ Result: When you open your
homepage, you’ll see “Welcome to Nobigdeal Training Centre”.
π« Classwork
- Create a view called about that
shows this text:
“This is Nobigdeal ICT Training Centre in Kubwa, Abuja.”
- Connect it to the /about/
path.
π Assignment
Create another view called contact that says:
“Call us at 0803-000-0000 or email: nobigdeal@gmail.com.”
π️ Day 2 (Tuesday):
Function-Based Views (FBV)
π― Lesson Objectives
Students should be able to:
- Write and understand function-based views.
- Use them to send text and data to a webpage.
- Connect multiple pages to different views.
π‘ 1. What is a
Function-Based View?
It’s a simple Python function that
handles a user’s request.
π Structure:
def view_name(request):
return HttpResponse("Response text here")
π§Ύ Example: Multiple Pages
views.py
from django.http import HttpResponse
def home(request):
return HttpResponse("Welcome to Nobigdeal Training Centre")
def about(request):
return HttpResponse("We train students in ICT and Graphics")
def services(request):
return HttpResponse("Services: Training, Printing, Online
Registration")
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
path('about/', views.about, name='about'),
path('services/', views.services, name='services'),
]
✅ Result:
- /
→ Homepage
- /about/ → About Page
- /services/ → Services Page
π« Classwork
Create a function view called contact that says:
“Visit us opposite Zenith Bank, Kubwa, Abuja.”
π Assignment
Create a view for /gallery/ that displays:
“Our Students in Practical Session.”
π️ Day 3 (Wednesday):
Class-Based Views (CBV)
π― Lesson Objectives
Students should be able to:
- Explain what Class-Based Views are.
- Convert Function-Based Views into Class-Based Views.
- Understand the use of .as_view().
π‘ 1. What is a Class-Based
View?
A Class-Based View uses a Python
class instead of a function.
It helps organize code neatly, especially for big projects.
π Structure:
from django.http import HttpResponse
from django.views import View
class HomeView(View):
def get(self, request):
return HttpResponse("This is the
Home Page")
urls.py
from django.urls import path
from .views import HomeView
urlpatterns = [
path('', HomeView.as_view(), name='home'),
]
✅ .as_view() is what
tells Django to treat the class like a view function.
π§Ύ Example: About and
Services with Class-Based Views
views.py
class AboutView(View):
def get(self, request):
return HttpResponse("We teach
students ICT and computer skills")
class ServicesView(View):
def get(self, request):
return HttpResponse("Our services
include training, printing, and registration")
π« Classwork
Convert your Day 2 function-based contact view into a class-based view.
π Assignment
Create a class-based view called GalleryView that displays:
“See photos from our previous training sessions.”
π️ Day 4 (Thursday): Views
and Templates
π― Lesson Objectives
Students should be able to:
- Connect Views with HTML templates.
- Display dynamic content using Django’s template system.
- Pass data from Views to Templates.
π‘ 1. Why Use Templates?
Templates make your site beautiful.
Instead of just plain text, you can design using HTML.
π§Ύ Example: Connecting a View
to a Template
views.py
from django.shortcuts import render
def home(request):
context = {'title': 'Welcome', 'center': 'Nobigdeal Training Centre'}
return render(request, 'home.html', context)
home.html (inside templates folder)
<!DOCTYPE html>
<html>
<head>
<title>{{ title }}</title>
</head>
<body>
<h1>Welcome to {{ center }}</h1>
</body>
</html>
✅ Result: Your site now looks
more like a real webpage.
π« Classwork
- Create a template called about.html.
- Pass and display this message:
“We are proud to train students in ICT, graphics, and coding.”
π Assignment
Create a template called contact.html that shows:
“You can reach us via email or visit our office at Kubwa.”
π️
Perfect! Let’s focus fully on Django Templates in a
beginner-friendly, student-centered, day-by-day format. I’ll explain what
they are, why they’re needed, components, examples, classwork, exercises, and
assignments.
π️ Day
1: Introduction to Django Templates
Topic: Templates in Django
Level: Beginner / Student-Centered Learning
Tools: VS Code, Python, Django installed
1. Lesson Objectives
By the end of this lesson, students
should be able to:
- Explain what a Template is in Django.
- Understand the purpose of using templates.
- Create simple HTML templates and connect them to Views.
2. What is a Template?
- A Template is an HTML file that
determines how your page looks.
- It is where you write the front-end design.
- Templates can use placeholders to display dynamic
content passed from Views.
π Nigerian Analogy:
Think of a Template as a menu card in a restaurant:
- The card (template) shows how the dishes will appear.
- The waiter (View) fills in the details (dynamic data)
like today’s special or customer name.
3. Why Use Templates?
- Separate Logic from Design – Keep Python code in Views and HTML in Templates.
- Dynamic Content
– Display information like student names, scores, or services dynamically.
- Reusable HTML
– One template can serve many pages by changing the data.
- Clean Code
– Easier to maintain large projects.
4. Components of a Template
Component
Description
Example
Template File
HTML file stored in templates/ folder
home.html
Placeholders
Dynamic content inside template
{{ name }}
Loops
Display lists of items
{% for service in
services %}
Conditionals
Show content based on condition
{% if
user.is_authenticated %}
Template Tags
Special Django syntax
{% block content %}
Template Filters
Modify output
`{{ name
5. Simple Example: Static Template
views.py
from django.shortcuts import render
def home(request):
return render(request, 'home.html')
home.html
<!DOCTYPE html>
<html>
<head>
<title>Home Page</title>
</head>
<body>
<h1>Welcome to Nobigdeal Training Centre</h1>
</body>
</html>
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
]
✅ Result: Visiting /
displays:
“Welcome to Nobigdeal Training Centre”
6. Example: Dynamic Template with
Context
views.py
def student_profile(request):
student = {'name': 'Amina', 'age': 12, 'grade': 'A'}
return render(request, 'profile.html', {'student': student})
profile.html
<h2>Student Profile</h2>
<p>Name: {{ student.name
}}</p>
<p>Age: {{ student.age
}}</p>
<p>Grade: {{ student.grade
}}</p>
✅ Result:
Student Profile
Name: Amina
Age: 12
Grade: A
7. Classwork / Exercises
- Create a View about and
template about.html that shows:
“We train and empower students in ICT.”
- Create a View services
passing a list of 3 services to services.html
and display them using a for loop.
- Optional: Create a contact page
passing phone and email dynamically to contact.html.
8. Solutions / Example Code
views.py
def about(request):
return render(request, 'about.html', {'info': 'We train and empower
students in ICT.'})
def services(request):
services_list = ['ICT Training', 'Graphic Design', 'Online
Registration']
return render(request, 'services.html', {'services': services_list})
def contact(request):
contact_info = {'phone': '0803-000-0000', 'email':
'nobigdeal@gmail.com'}
return render(request, 'contact.html', {'contact': contact_info})
services.html
<h1>Our Services</h1>
<ul>
{% for service in services %}
<li>{{ service }}</li>
{% endfor %}
</ul>
contact.html
<h1>Contact Us</h1>
<p>Phone: {{ contact.phone
}}</p>
<p>Email: {{ contact.email
}}</p>
9. Homework / Assignment
- Create a gallery page
and template showing 3 images of previous training sessions.
- Pass your name dynamically to the home page using
context:
“Welcome, [Your Name], to Nobigdeal Training Centre!”
10. Summary Table
Term
Meaning
(Nigeria Example)
Example
Template
HTML file for display
home.html
Context
Data passed from View to Template
{'name': 'Amina'}
render()
Connects View to Template
render(request,
'home.html', context)
Placeholder
Where dynamic content appears
{{ name }}
Loop
Display list of items
{% for service in
services %}
Conditional
Show content based on condition
{% if student.grade
== "A" %}
Perfect! Let’s move to Day 2: Using Loops and Conditionals in Django Templates with full explanations, examples, classwork, exercises, and assignments.
π️ Day 2: Loops and Conditionals in Django Templates
Topic: Dynamic Content with Loops and Conditionals
Level: Beginner / Student-Centered Learning
Tools: VS Code, Python, Django installed
1. Lesson Objectives
By the end of this lesson, students should be able to:
-
Display lists of data dynamically using loops.
-
Show or hide content using conditionals.
-
Combine loops and conditionals in templates.
-
Practice passing lists and variables from Views to Templates.
2. Loops in Templates
What is a Loop?
-
A loop repeats a set of instructions for each item in a list.
-
In templates, loops help display multiple items dynamically.
π Nigerian Analogy:
Think of loop as listing all items in a market:
-
“For each item on the shelf, show its name and price.”
Example: Display a List of Services
views.py
def services(request):
services_list = ['ICT Training', 'Graphic Design', 'Online Registration']
return render(request, 'services.html', {'services': services_list})
services.html
<h1>Our Services</h1>
<ul>
{% for service in services %}
<li>{{ service }}</li>
{% endfor %}
</ul>
✅ Result:
-
ICT Training
-
Graphic Design
-
Online Registration
3. Conditionals in Templates
What is a Conditional?
-
A conditional shows or hides content depending on a condition.
-
Uses {% if %}, {% elif %}, and {% else %} in templates.
π Nigerian Analogy:
-
If it’s raining, we stay indoors; else, we go to the market.
Example: Display Pass/Fail Status
views.py
def student_status(request):
student = {'name': 'Amina', 'score': 65}
return render(request, 'status.html', {'student': student})
status.html
<h2>Student Status</h2>
<p>Name: {{ student.name }}</p>
{% if student.score >= 50 %}
<p>Status: Pass</p>
{% else %}
<p>Status: Fail</p>
{% endif %}
✅ Result:
-
Name: Amina
-
Status: Pass
4. Combining Loops and Conditionals
Example: Multiple Students with Pass/Fail
views.py
def students(request):
students_list = [
{'name': 'Amina', 'score': 65},
{'name': 'John', 'score': 45},
{'name': 'Sade', 'score': 80},
]
return render(request, 'students.html', {'students': students_list})
students.html
<h2>Students Scores</h2>
<ul>
{% for student in students %}
<li>{{ student.name }} - Score: {{ student.score }} -
{% if student.score >= 50 %}Pass{% else %}Fail{% endif %}</li>
{% endfor %}
</ul>
✅ Result:
-
Amina - Score: 65 - Pass
-
John - Score: 45 - Fail
-
Sade - Score: 80 - Pass
5. Classwork / Exercises
-
Create a View products that passes a list of 5 products with name and price to products.html.
-
Use a loop to display all products.
-
Create a View employees that passes a list of employee dictionaries (name + salary).
-
Show “High Salary” if salary > 100000, else “Low Salary” using conditionals.
-
Optional: Combine a loop and conditional to highlight products costing > ₦5000 in bold.
6. Solutions / Example Code
views.py
def products(request):
products_list = [
{'name': 'Laptop', 'price': 120000},
{'name': 'Phone', 'price': 50000},
{'name': 'Mouse', 'price': 2000},
{'name': 'Keyboard', 'price': 4000},
{'name': 'Printer', 'price': 15000},
]
return render(request, 'products.html', {'products': products_list})
def employees(request):
employees_list = [
{'name': 'Amina', 'salary': 120000},
{'name': 'John', 'salary': 80000},
{'name': 'Sade', 'salary': 95000},
]
return render(request, 'employees.html', {'employees': employees_list})
products.html
<h1>Products</h1>
<ul>
{% for product in products %}
<li>{{ product.name }} - ₦{{ product.price }}</li>
{% endfor %}
</ul>
employees.html
<h1>Employees</h1>
<ul>
{% for employee in employees %}
<li>{{ employee.name }} - ₦{{ employee.salary }} -
{% if employee.salary > 100000 %}High Salary{% else %}Low Salary{% endif %}</li>
{% endfor %}
</ul>
7. Homework / Assignment
Create a courses page and template with a list of 5 courses.
Highlight courses with more than 30 students in bold.
Create a tasks page that passes a list of tasks with a completed boolean.
Show “Done” if completed, else “Pending”.
8. Summary Table
Concept
Meaning (Nigeria Example)
Example
Loop
Repeat for each item
{% for product in products %}
Conditional
Show/hide content based on a condition
{% if score >= 50 %}
Loop + Conditional
Combine for multiple items with conditions
Students Pass/Fail example
Placeholder
Where dynamic data appears
{{ student.name }}
Context
Data passed from View
{'students': students_list}
URLs
-
What: Web address that tells Django which view to use.
-
Why: Connect pages, make site organized, handle dynamic content.
-
Learn before: Views, Python functions/classes, HTML links.
Example:
from django.urls import path
from . import views
urlpatterns = [
path('students/', views.student_list, name='student_list'),
]
Admin Interface
-
What: A ready-made dashboard in Django to manage your data.
-
Why: You can add, edit, delete, or view data without writing code.
-
Learn before: Models (so you know what data you have).
Example:
from django.contrib import admin
from .models import Student
admin.site.register(Student)
-
This lets you see and manage Student data in the admin panel.
Forms
-
What: A way to collect user input (like registration forms).
-
Why: Helps users send data to your app safely and easily.
-
Learn before: Models, views, templates, basic HTML forms.
Example:
from django import forms
from .models import Student
class StudentForm(forms.ModelForm):
class Meta:
model = Student
fields = ['name', 'age', 'email']
-
This form lets users add or edit Student info in your website.
Middleware
-
What: A tool that processes requests and responses automatically.
-
Why: Can do tasks like check login, security, sessions, or data changes.
-
Learn before: Views and URLs, basic Python.
Example:
-
Middleware can check if a user is logged in before allowing them to see a page.
MVT Architecture
-
MVT = Model – View – Template
-
Model: Handles data.
-
View: Handles logic and decides what to show.
-
Template: Handles the design (what users see).
Simple idea: Django separates your data, logic, and design for easy management.
ORM (Object Relational Mapper)
-
What: Lets you work with databases using Python, no SQL needed.
-
Why: Easier and safer to handle data.
-
Learn before: Models, Python basics, database concepts.
Example:
students = Student.objects.all() # Get all students
-
This gets all students from the database using Python code, not SQL.
Security
-
What: Built-in tools in Django to protect your app.
-
Why: Prevents attacks like hacking, fake forms, or data theft.
-
Learn before: Basic views, templates, and forms.
Example:
-
CSRF protection automatically checks forms to prevent fake submissions.
Summary of Django Components in Simple Words
| Component | What It Does | Why Use It |
|---|---|---|
| Model | Store data | Organize and manage database easily |
| View | Logic, decides what to show | Make app dynamic |
| Template | Design pages | Show data to users nicely |
| URL | Web address | Connect pages to views |
| Admin | Dashboard | Manage data easily |
| Forms | Collect input | Users can send data safely |
| Middleware | Process requests/responses | Handle login, security, sessions |
| MVT | Structure (Model-View-Template) | Keep data, logic, and design separate |
| ORM | Work with database using Python | Easier than SQL |
| Security | Protect your app | Prevent attacks |
Day 3: Python classes,
Perfect, Raheem! Let’s explain Python classes in very simple English for your students without using “blueprint”, and also explain objects and key terms..
1. Field Types in Django
What is it?
-
Field types tell Django what kind of information each part of your model will store.
Common Field Types
| Field Type | Stores | Example Use |
|---|---|---|
CharField |
Short text | Name, Title |
TextField |
Long text | Description, Notes |
IntegerField |
Whole numbers | Age, Quantity |
FloatField |
Decimal numbers | Price, Height |
BooleanField |
True / False | Is_active, Published |
DateField |
Date only | Birthday, Start Date |
DateTimeField |
Date + Time | Created_at, Updated_at |
EmailField |
Email address | Student or teacher email |
URLField |
Website link | Portfolio, company website |
FileField |
Upload a file | PDF, document |
ImageField |
Upload an image | Profile picture, product image |
DecimalField |
Decimal numbers | Price, salary |
Example Model Using Field Types
from django.db import models
class Student(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
bio = models.TextField()
email = models.EmailField()
joined_date = models.DateField()
is_active = models.BooleanField(default=True)
2. Database Basics
What is it?
-
A database is where your app stores information.
-
Django creates a table in the database for each model.
Key Terms:
| Term | Meaning |
|---|---|
| Table | Stores all data for a model |
| Row / Record | One item of data |
| Column / Field | Type of information (name, age, etc) |
| Primary Key | Unique ID for each row (Django adds it automatically) |
Example: Student Table
| id | name | age | bio | joined_date | is_active |
|---|---|---|---|---|---|
| 1 | Ali | 12 | Likes maths | 2025-01-01 | True |
| 2 | Zara | 14 | Likes science | 2025-02-01 | True |
-
Each model → table
-
Each object → row in table
3. Migrations
What is it?
-
Migrations are how Django updates the database when you create or change models.
When to Use:
-
When you create a new model.
-
When you change a field or add/remove a field.
Where to Use:
-
Terminal / Command Prompt in your Django project folder.
How to Use:
-
Create migration (tell Django about changes):
python manage.py makemigrations
-
Apply migration (update database):
python manage.py migrate
Example Workflow:
-
Create model
Student→makemigrations→migrate→ Table created in database -
Add a new field
grade→makemigrations→migrate→ Table updates
Classwork Example
-
Create a model
Teacherwith:-
name(CharField) -
subject(CharField) -
age(IntegerField) -
hire_date(DateField) -
is_active(BooleanField)
-
-
Make migrations and migrate.
-
Check the table in the database.
Assignment Example
-
Create a model
Bookwith:-
title(CharField) -
author(CharField) -
pages(IntegerField) -
published_date(DateField) -
available(BooleanField)
-
-
Make migrations and migrate.
-
Add 3 book objects using Django admin.
-
Bonus: Add a
genrefield later, make migrations, and migrate.
Day 5: Assessment
Perfect, Raheem! Here’s a simple assessment for your students on Field Types, Database Basics, and Migrations. It’s easy to understand and can be done in Django.
Assessment: Django Field Types, Database, and Migrations
Part A: Theory Questions
-
What is a field type in Django? Give two examples.
-
What is a database? What is a table in a database?
-
What is an object in Django?
-
What is a migration and why is it important?
-
Name three common field types in Django and what they store.
Part B: Practical Questions
Task 1: Create a Django model Student with the following fields:
-
name→ CharField (max_length=100) -
age→ IntegerField -
email→ EmailField -
joined_date→ DateField -
is_active→ BooleanField
Steps:
-
Create the model in
models.py. -
Make migrations and migrate.
-
Add 2 student objects using Django admin.
-
Check the database table to see if rows are created.
Task 2: Create a Django model Book with the following fields:
-
title→ CharField (max_length=200) -
author→ CharField (max_length=100) -
pages→ IntegerField -
published_date→ DateField -
available→ BooleanField
Steps:
-
Create the model in
models.py. -
Make migrations and migrate.
-
Add 3 book objects using Django admin.
-
Bonus: Add a
genre(CharField) later, make migrations, and migrate.
Task 3 (Extra Challenge):
-
Create a
Teachermodel withname(CharField) andsubject(CharField). -
Create a
Coursemodel withtitle(CharField) and aManyToManyFieldlinking toTeacher. -
Make migrations and migrate.
How a Django Model Works
1. Model is a Python Class
-
Each model is a Python class inside
models.py. -
Each attribute (field) in the class becomes a column in the database table.
-
Each object (instance) of the model becomes a row in the table.
Example:
from django.db import models
class Student(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
email = models.EmailField()
joined_date = models.DateField()
is_active = models.BooleanField(default=True)
What happens here:
-
Student→ table name -
name,age,email→ columns in the table -
Each student added → one row in the table
2. Model Creates a Table in Database
-
Django automatically creates a table when you run migrations.
-
Command:
python manage.py makemigrations
python manage.py migrate
-
✅ Now the table exists in the database.
3. Model Stores Data (Objects)
-
You can add objects to the model, which Django saves as rows in the table.
Example (using shell):
from myapp.models import Student
student1 = Student(name="Ali", age=12, email="ali@mail.com", joined_date="2025-01-01", is_active=True)
student1.save() # Saves to database
4. Model Retrieves Data
-
Django provides a simple way to get data from the database using
objects:
students = Student.objects.all() # Get all students
student = Student.objects.get(id=1) # Get student with ID 1
active_students = Student.objects.filter(is_active=True) # Filter students
5. Model Updates Data
-
You can change a field and save it:
student = Student.objects.get(id=1)
student.age = 13
student.save() # Update database
6. Model Deletes Data
-
You can delete an object, which removes it from the table:
student = Student.objects.get(id=1)
student.delete()
7. How it Works Internally (Step by Step)
-
You create a model → Python class in
models.py. -
Django reads the model and creates a database table (columns = fields).
-
You create objects → Django inserts rows in the table.
-
You query objects → Django fetches rows from the table.
-
You update objects → Django updates rows in the table.
-
You delete objects → Django removes rows from the table.
8. Simple Diagram
Model (Python class)
│
▼
Fields (columns in table)
│
▼
Object (row in table)
│
▼
Database Table
Classwork Example
-
Create a model
Teacherwith fields:-
name,subject,age,hire_date,is_active
-
-
Make migrations and migrate.
-
Add 2 teacher objects.
-
Retrieve all teachers and print their names.
-
Update one teacher’s age.
-
Delete one teacher.
Assignment Example
-
Create a model
Bookwith fields:-
title,author,pages,published_date,available
-
-
Make migrations and migrate.
-
Add 3 book objects.
-
Retrieve all books.
-
Update the number of pages for one book.
-
Delete one book.
By default, Django uses SQLite, which is a file-based database.
-
Look in your project folder. You will see a file called:
db.sqlite3
-
✅ This file stores all your data and tables.
Note: If you are using MySQL or PostgreSQL, the database is on the server you set in
settings.py.
2. See the Tables in the Database
A. Using SQLite Browser (Recommended for Beginners)
-
Download DB Browser for SQLite (free).
-
Open db.sqlite3 in the app.
-
You will see all tables Django created.
-
Example:
myapp_student,myapp_teacher
-
-
Click on a table to see its rows and columns (your data).
B. Using Django Shell
-
Open Django shell in terminal:
python manage.py shell
-
Import your model and see data:
from myapp.models import Student
Student.objects.all() # Shows all records in Student table
-
✅ Each object corresponds to a row in the table.
C. Using Django Admin Panel
-
Register your model in
admin.py:
from django.contrib import admin
from .models import Student
admin.site.register(Student)
-
Run the server:
python manage.py runserver
-
Open
http://127.0.0.1:8000/admin/and login. -
You will see Student table and all its rows.
3. Notes
-
Table name =
appname_modelname(all lowercase) -
Columns = model fields
-
Rows = objects/entries
Classwork Example
-
Create a model
Teacherwithnameandsubject. -
Make migrations and migrate.
-
Open db.sqlite3 in DB Browser.
-
Add a teacher in admin and see it in the table.
Assignment Example
-
Create a model
Bookwithtitle,author,pages. -
Make migrations and migrate.
-
Open db.sqlite3 and locate the
Booktable. -
Add 3 book entries in admin and check the table.
Got it, Raheem! Let’s explain how to use Django templates in very simple English with examples and practical steps for your students.
Django Templates
1. What is a Template?
-
A template is an HTML file that decides how your webpage looks.
-
Templates can show dynamic data from your views using Django template tags.
Simple idea: Templates are the face of your website, showing information to users.
2. Why Use Templates?
-
To separate HTML (design) from Python code (logic).
-
To show data from models or views on a web page.
-
To use loops, conditions, and filters in HTML.
3. Where to Put Templates
-
Inside your app folder, create a folder called
templates. -
Example structure:
myapp/
templates/
myapp/
student_list.html
Django looks for templates in
app/templates/app_name/by default.
4. How to Connect Views and Templates
-
Create a view that sends data to the template:
# views.py
from django.shortcuts import render
from .models import Student
def student_list(request):
students = Student.objects.all()
return render(request, 'myapp/student_list.html', {'students': students})
-
Create a URL for the view:
# urls.py
from django.urls import path
from . import views
urlpatterns = [
path('students/', views.student_list, name='student_list'),
]
-
Create the template file
student_list.html:
<h1>Student List</h1>
<ul>
{% for student in students %}
<li>{{ student.name }} - {{ student.age }}</li>
{% endfor %}
</ul>
5. Template Tags
-
{{ variable }}→ Shows data from views. -
{% for item in list %} ... {% endfor %}→ Loops through items. -
{% if condition %} ... {% endif %}→ Conditional statements.
6. How it Works
-
User visits a URL (e.g.,
/students/). -
Django runs the view (
student_list). -
View gets data from model (
Student.objects.all()). -
View sends data to template.
-
Template shows data as HTML page.
7. Classwork Example
-
Create a model
Teacherwithnameandsubject. -
Create a view
teacher_listthat gets all teachers. -
Create a template
teacher_list.htmlto show all teachers. -
Connect URL
/teachers/to the view. -
Open browser and check the page.
8. Assignment Example
-
Create a model
Bookwith fieldstitle,author,pages. -
Create a view
book_listto get all books. -
Create a template
book_list.htmlthat shows all books. -
Add a URL
/books/to connect the view. -
Test in the browser.
-
Bonus: Add a loop to highlight books with more than 200 pages using
{% if %}tag.
Got it, Raheem! Let’s explain Django URLs in very simple English with examples and practical steps.
Django URLs
1. What is a URL?
-
A URL (Uniform Resource Locator) is a web address that tells Django which page or view to show.
-
Example:
http://127.0.0.1:8000/students/
-
This URL tells Django to run a specific view that shows all students.
Simple idea: URLs are like road signs, guiding users to the right page.
2. Why Use URLs?
-
To connect a web address to a view.
-
To make your website organized and easy to navigate.
-
To handle dynamic content, e.g.,
/student/1/shows student with ID 1.
3. Where to Create URLs
-
Each app has a
urls.pyfile (if not, you can create one). -
The project folder also has a main
urls.pyfile. -
You connect app URLs to project URLs for the site to work.
4. How to Create URLs
A. App URL
# myapp/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('students/', views.student_list, name='student_list'),
]
B. Project URL
# myproject/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('myapp.urls')), # Connects app URLs
]
5. How it Works
-
User visits a URL in the browser.
-
Django matches the URL to a path in urls.py.
-
Django runs the view connected to that URL.
-
The view sends data to template, and the page is shown.
6. URL Examples
-
/students/→ Shows all students. -
/student/1/→ Shows student with ID 1. -
/books/→ Shows all books. -
/book/5/→ Shows book with ID 5.
Optional: You can give each URL a name to use it in templates:
<a href="{% url 'student_list' %}">Students</a>
7. Classwork Example
-
Create a view
teacher_listthat shows all teachers. -
Create a URL
/teachers/that runs the view. -
Test in the browser and see the list of teachers.
8. Assignment Example
-
Create a view
book_listthat shows all books. -
Create a URL
/books/that runs the view. -
Bonus: Create another URL
/books/<int:id>/to show a single book’s details. -
Test both URLs in the browser.
Sure, Raheem! Let’s explain each of these Django components in very simple English, with examples and practical notes for your students.
1. Admin – Dashboard to Manage Data
What is Admin?
-
Django gives you a ready-made dashboard to manage your data.
-
You don’t need to create forms or pages to add, edit, or delete data.
Why Use Admin?
-
Quickly manage your models (tables).
-
See all records in a clean interface.
-
Easy to add users, posts, students, books, etc.
How to Use Admin
-
Register your model in
admin.py:
from django.contrib import admin
from .models import Student
admin.site.register(Student)
-
Run the server:
python manage.py runserver
-
Go to
http://127.0.0.1:8000/admin/and login. -
You can add, update, or delete student records.
2. MVT Architecture – Structure (Model-View-Template)
What is MVT?
-
MVT = Model, View, Template
-
It is Django’s way to organize code.
| Component | Role |
|---|---|
| Model | Stores data (database) |
| View | Handles logic, connects Model & Template |
| Template | Shows data on a web page |
Simple idea:
-
Model → stores data
-
View → decides what to show
-
Template → shows it to users
3. Middleware – Process Requests and Responses
What is Middleware?
-
Middleware is a layer between user and app.
-
It processes requests before views run and responses before reaching the browser.
Why Use Middleware?
-
Handle security (e.g., block bad users).
-
Manage sessions, authentication, or logging.
-
Modify request or response if needed.
Example:
# settings.py
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
]
4. Forms – Collect User Input
What are Forms?
-
Forms let users submit data (like registration, feedback, or comments).
Why Use Forms?
-
To safely get input from users.
-
To validate data before saving to the database.
Example:
from django import forms
class StudentForm(forms.Form):
name = forms.CharField(max_length=100)
age = forms.IntegerField()
5. ORM – Use Python to Work with Databases
What is ORM?
-
ORM = Object Relational Mapping
-
Lets you use Python code to create, read, update, delete data instead of SQL.
Example:
# Add a student
student = Student(name="Ali", age=12)
student.save()
# Get all students
students = Student.objects.all()
6. Security – Protect the App
What is Security in Django?
-
Django has built-in protections for your app:
-
SQL injection
-
Cross-site scripting (XSS)
-
Cross-site request forgery (CSRF)
-
Why Important?
-
Keeps user data safe.
-
Protects your website from attacks.
Example: CSRF token in templates:
<form method="post">
{% csrf_token %}
<input type="text" name="name">
<button type="submit">Submit</button>
</form>
Classwork Example
-
Register
Studentmodel in admin and add 2 students. -
Create a form for students to submit data.
-
Use ORM to retrieve and update a student.
-
Check CSRF token in template for security.
Assignment Example
-
Create
Bookmodel and register in admin. -
Make a form to add books.
-
Use ORM to get all books and filter available books.
-
Add CSRF token to the form template.
-
Bonus: Explain how MVT works using your
Bookmodel.
Month 3:
Got it, Raheem! Let’s make a very simple Django project that covers all the components you’ve learned:
Project Idea: Student Management System
This project will cover:
-
Model → store students
-
Admin → manage students
-
View → logic to display students
-
Template → show students in HTML
-
URL → connect pages
-
Forms → add new students
-
ORM → work with database in Python
-
Middleware & Security → default Django protections
Step-by-Step Project
1. Create Django Project
django-admin startproject school
cd school
python manage.py startapp students
2. Create Model
# students/models.py
from django.db import models
class Student(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
email = models.EmailField()
joined_date = models.DateField(auto_now_add=True)
is_active = models.BooleanField(default=True)
def __str__(self):
return self.name
3. Make Migrations
python manage.py makemigrations
python manage.py migrate
4. Register in Admin
# students/admin.py
from django.contrib import admin
from .models import Student
admin.site.register(Student)
-
Run server and go to
http://127.0.0.1:8000/admin/to add students.
5. Create View
# students/views.py
from django.shortcuts import render
from .models import Student
from .forms import StudentForm
def student_list(request):
students = Student.objects.all()
return render(request, 'students/student_list.html', {'students': students})
def add_student(request):
if request.method == 'POST':
form = StudentForm(request.POST)
if form.is_valid():
form.save() # Saves data using ORM
else:
form = StudentForm()
return render(request, 'students/add_student.html', {'form': form})
6. Create Form
# students/forms.py
from django import forms
from .models import Student
class StudentForm(forms.ModelForm):
class Meta:
model = Student
fields = ['name', 'age', 'email', 'is_active']
7. Create Templates
student_list.html
<h1>Student List</h1>
<ul>
{% for student in students %}
<li>{{ student.name }} - {{ student.age }} - {{ student.email }}</li>
{% endfor %}
</ul>
<a href="{% url 'add_student' %}">Add Student</a>
add_student.html
<h1>Add Student</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Add</button>
</form>
<a href="{% url 'student_list' %}">Back to List</a>
8. Set URLs
# students/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('students/', views.student_list, name='student_list'),
path('students/add/', views.add_student, name='add_student'),
]
# school/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('students.urls')),
]
9. Test the Project
-
Run server:
python manage.py runserver
-
Go to:
-
http://127.0.0.1:8000/students/→ View student list -
http://127.0.0.1:8000/students/add/→ Add a student -
http://127.0.0.1:8000/admin/→ Manage students in admin
-
What This Project Covers
| Feature | Covered By |
|---|---|
| Model | Student model |
| Admin | Admin panel to manage students |
| View | student_list & add_student views |
| Template | student_list.html & add_student.html |
| URL | URLs connected to views |
| Form | StudentForm to add data |
| ORM | form.save() and Student.objects.all() |
| Middleware & Security | Default Django middleware, CSRF token |
Classwork Idea
-
Add a Teacher model similar to Student.
-
Create list and add pages for teachers using templates, views, forms, and URLs.
Assignment Idea
-
Add a Book model with fields:
title,author,pages,available. -
Create admin, view, template, form, and URLs to add and display books.


0 comments:
Post a Comment