Assignment: Build a screen with:1. A <TextInput>
to enter student names.2. A <Button> labeled “Add Student”.3. Style the input and button
nicely (colors, padding).
Sunday (Class 3)
·Introduce
useState to save input values.
·Display
added names using .map() or FlatList.
·Mini
Project: Add Student Name → Show in List.
Assignment: Complete the mini project:1. Add at least 3 student
names.2. Display them in a list.3. Style the list (different colors or borders).
WEEK
2
Day
Topics
/ Activities
Assignment
Thursday (Class 4)
Add Navigation (Home ↔
Student List). Pass data using props. Link multiple screens.
Assignment: Build 2 screens:1. Home screen with a welcome message.2.
Student List screen that displays names.3. Navigate from Home → List.
Saturday (Class 5)
Add delete/edit feature for
student info. Arrange layout with Flexbox. Add background colors,
spacing, and borders.
Assignment: Update your Student List app:1. Add a delete button to
remove a student.2. Optional: add an edit button to change a student name.3.
Improve layout and design.
Sunday (Class 6)
Review all lessons. Test app on
real devices using Expo Go. Students present their Student Info App
project.
Final Project: Submit and present:1. Fully working Student Info App.2.
Add at least 5 students.3. Include navigation and delete/edit features.4.
Styled and polished design.
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(), or str().
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.
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 the if 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".
# Ask the user to enter a number
number = int(input("Enter a number: "))
# Check if the number is even or odd
if number % 2 == 0:
print("The number is even.")
else:
print("The number is 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 withtitleandauthor. Print all books.
Assignment:
Create a list of 3 teachers, each withnameandsubject. 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
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
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
3️⃣ Set
Meaning:
A set is a collection of unique items, meaning no duplicates.
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 and s2 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.
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)
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)
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 called schoolpackage.
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.
🧩 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 datetime library.
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)
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.
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.
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:
print("Hello, World!")
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.
Add another view called about and create about.html
10️⃣ Assignment
Create 2 more pages: contact and services
Each page should have a different message and heading
Update urls.py to 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 about that will return a template about.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.
“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.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 and migrate 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 before migrate?” → 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 and migrate
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']
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
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']
# 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:
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.
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 about that displays: “This is Nobigdeal ICT Training Centre in Kubwa, Abuja.”
Connect it to /about/ URL.
Create a Class-Based View called services that 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")
Create a view contact that 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")
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 Viewcontact that displays: “Call us at 0803-000-0000 or email nobigdeal@gmail.com”
Connect it to /contact/.
Create another FBV gallery that displays: “Check our previous training session photos.”
Bonus: Add a context dictionary to home page 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.")
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 about that 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")
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 about that displays: “Nobigdeal Training Centre is the best ICT training centre in Abuja.”
Create a CBV services page 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
<h1>Student List</h1>
<ul>
{% for student in students %}
<li>{{ student.name }} - {{ student.age }}</li>
{% endfor %}
</ul>
Perfect ✅
— let’s create acomplete 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")
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”
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.”
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 with name (CharField) and subject (CharField).
Create a Course model with title (CharField) and a ManyToManyField linking to Teacher.
Make migrations and migrate.
Week 2: How Model works
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.
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
# 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>