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) / 3
and 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:
-
if
checks 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:
-
else
runs if theif
condition 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:
-
elif
checks 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
if
inside 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:
-
for
loop 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:
-
while
loop 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
title
andauthor
. Print all books.
Assignment:
Create a list of 3 teachers, each with
name
andsubject
. 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:
-
Student
is the class (blueprint) -
s1
ands2
are 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.py
and use it in another program.
🔹 4. How to Use a Module
(a) Using a Built-in Module
import math
print(math.sqrt(16)) # 4.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
(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
mypackage
with 2 modules. Write one function in each module.
Assignment:
-
Import functions from both modules in a main file and use them.
Perfect ✅ Let's make the teaching on Python Packages very simple, easy, and teacher-centered — just the way you teach beginners step by step from Monday to Friday.
This version uses short, simple examples and easy words for classroom use.
🧭 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
math
andrandom
. -
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
.py
files.
💻 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
student
from 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__.py
file. -
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.
📁 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
mysite
is 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.
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.
Absolutely! Let’s make Day 1 fully beginner-friendly with a very simple Django model example that a student can understand and implement easily. I’ll explain every part in plain language.
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.py
in 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
makemigrations
andmigrate
in 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
makemigrations
beforemigrate
?” →makemigrations
creates the instructions;migrate
executes 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
Book
model 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
makemigrations
andmigrate
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
myapp
with 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)
-
s1
is 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
Teacher
model 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
Book
model 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 shell
to 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
Course
model 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.
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>
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
Teacher
with:-
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
Book
with:-
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
genre
field 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
Teacher
model withname
(CharField) andsubject
(CharField). -
Create a
Course
model withtitle
(CharField) and aManyToManyField
linking 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
Teacher
with 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
Book
with 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
Teacher
withname
andsubject
. -
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
Book
withtitle
,author
,pages
. -
Make migrations and migrate.
-
Open db.sqlite3 and locate the
Book
table. -
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
Teacher
withname
andsubject
. -
Create a view
teacher_list
that gets all teachers. -
Create a template
teacher_list.html
to show all teachers. -
Connect URL
/teachers/
to the view. -
Open browser and check the page.
8. Assignment Example
-
Create a model
Book
with fieldstitle
,author
,pages
. -
Create a view
book_list
to get all books. -
Create a template
book_list.html
that 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.py
file (if not, you can create one). -
The project folder also has a main
urls.py
file. -
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_list
that 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_list
that 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
Student
model 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
Book
model 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
Book
model.
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.