Tuesday, October 7, 2025

Python Django

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:

  1. int → whole numbers

  2. float → decimal numbers

  3. str → text

  4. 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 12 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 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".

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 

Week 1: Functions and Loops

Objective: Learn how to reuse code and repeat tasks — important for Django views.


Class 1: What is a Function?

Explanation:

  • A function is a block of code that does a task.

  • We use functions to avoid repeating the same code.

  • In Django, views are often functions that decide what the user sees.

Example:

def greet(name):
    print(f"Hello, {name}!")

greet("Raheem")  # Output: Hello, Raheem!
greet("Aisha")   # Output: Hello, Aisha!

Classwork:

  • Ask students to create a function that prints their favorite food.

Assignment:

  • Create a function add_numbers that adds 2 numbers and prints the result.


Class 2: Function with Return

Explanation:

  • Functions can return a value instead of just printing it.

  • Return values can be used in other parts of the program.

Example:

def add(a, b):
    return a + b

result = add(5, 3)
print(result)  # Output: 8

Classwork:

  • Make a function multiply(a, b) that returns the product of 2 numbers.

Assignment:

  • Create a function calculate_age(birth_year) that returns age (assume current year is 2025).


Class 3: Loops – For Loop

Explanation:

  • A for loop repeats code for each item in a list or range.

  • In Django, we use loops to display lists of data in templates.

Example:

students = ["Ali", "Aisha", "Emmanuel"]
for student in students:
    print(student)

Classwork:

  • Loop through a list of 5 colors and print each color.

Assignment:

  • Create a list of 5 fruits and print each fruit in uppercase.


Class 4: Loops – While Loop

Explanation:

  • A while loop repeats code while a condition is true.

  • Useful when you don’t know exactly how many times you need to repeat.

Example:

i = 1
while i <= 5:
    print(i)
    i += 1

Classwork:

  • Print numbers from 10 to 1 using a while loop.

Assignment:

  • Create a program that asks the user to enter a password. Keep asking until the correct password is entered.


Class 5: Functions + Loops Together

Explanation:

  • Functions and loops can be combined to do repetitive tasks automatically.

Example:

def print_students(students):
    for student in students:
        print(f"Student Name: {student}")

students_list = ["Ali", "Aisha", "Emmanuel"]
print_students(students_list)

Classwork:

  • Create a function that prints numbers from 1 to 10.

Assignment:

  • Create a function even_numbers(numbers) that prints only the even numbers from a list.


Class 6: Mini Project

Task:

  • Create a function show_student_info(students)

  • Input: list of dictionaries with name and age

  • Output: print each student’s name and age

Example:

students = [
    {"name": "Ali", "age": 12},
    {"name": "Aisha", "age": 13}
]

def show_student_info(students):
    for s in students:
        print(f"{s['name']} is {s['age']} years old")

show_student_info(students)

Outcome: Students understand functions, loops, and lists together.


Class 7: Review & Practice

  • Solve small exercises combining functions + loops + lists.

  • Discuss questions and clarify doubts.

Perfect, Raheem! Let’s continue with Week 2: Classes and Objects in a simple and practical way.


Week 2: Classes and Objects

Objective: Learn how to create and use objects — important for Django models.


Class 1: What is a Class?

Explanation:

  • A class is like a blueprint for creating objects.

  • It groups data (attributes) and actions (methods/functions) together.

  • In Django, models are classes that represent database tables.

Example:

class Student:
    pass

# This is an empty class

Classwork:

  • Ask students to create an empty class called Teacher.

Assignment:

  • Create a class called Book. Don’t add anything yet.


Class 2: Creating Objects

Explanation:

  • Objects are instances of a class.

  • They store real data using the class blueprint.

Example:

class Student:
    name = ""
    age = 0

student1 = Student()
student1.name = "Ali"
student1.age = 12

print(student1.name, student1.age)  # Output: Ali 12

Classwork:

  • Create 2 Student objects with different names and ages.

Assignment:

  • Create 2 Book objects with title and author.


Class 3: Methods in Classes

Explanation:

  • Methods are functions inside classes that perform actions on objects.

Example:

class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def info(self):
        print(f"{self.name} is {self.age} years old")

student1 = Student("Aisha", 13)
student1.info()  # Output: Aisha is 13 years old

Classwork:

  • Create a method greet() in the Student class that says hello to the student.

Assignment:

  • Add a method details() in the Book class that prints title and author.


Class 4: Constructor (init)

Explanation:

  • The __init__ method automatically sets values when creating an object.

  • It saves time instead of setting attributes manually.

Example:

class Teacher:
    def __init__(self, name, subject):
        self.name = name
        self.subject = subject

teacher1 = Teacher("Mr. John", "Math")
print(teacher1.name, teacher1.subject)  # Output: Mr. John Math

Classwork:

  • Create a class Car with attributes brand and color using __init__.

Assignment:

  • Create 3 Book objects with title and author using __init__.


Class 5: List of Objects

Explanation:

  • You can store multiple objects in a list and loop through them.

Example:

students = [
    Student("Ali", 12),
    Student("Aisha", 13),
    Student("Emmanuel", 14)
]

for s in students:
    s.info()

Classwork:

  • Create a list of 3 teachers and print their names and subjects.

Assignment:

  • Create a list of 3 books and print their title and author using a loop.


Class 6: Mini Project

Task: Create a small program using class and objects

  • Class: Book

  • Attributes: title, author, pages

  • Method: details() prints book info

  • Store multiple books in a list and print all details

Example:

class Book:
    def __init__(self, title, author, pages):
        self.title = title
        self.author = author
        self.pages = pages

    def details(self):
        print(f"{self.title} by {self.author}, {self.pages} pages")

books = [
    Book("Python Basics", "Ali", 150),
    Book("Django for Beginners", "Aisha", 200)
]

for book in books:
    book.details()

Outcome:

  • Students understand classes, objects, methods, lists of objects — all needed for Django models.


Class 7: Revision & Practice

  • Combine multiple classes and loops

  • Ask students to create Student, Teacher, and Book classes and print info in a structured way


Great, Raheem! Let’s continue with Week 3: Modules, Packages, and File Handling. I’ll keep it simple, with examples, classwork, and assignments.


Week 3: Modules, Packages, and File Handling

Objective: Learn how to organize code and work with files — important for Django apps and templates.


Class 1: What is a Module?

Explanation:

  • A module is a Python file that contains code (functions, classes, or variables).

  • We use modules to organize code and reuse it.

  • Django uses modules for views, models, and utilities.

Example:

# mymodule.py
def greet(name):
    return f"Hello, {name}!"

# main.py
import mymodule
print(mymodule.greet("Raheem"))  # Output: Hello, Raheem!

Classwork:

  • Create a module math_utils.py with a function add(a,b) that returns sum.

  • Import it in another file and use it.

Assignment:

  • Create a module string_utils.py with a function uppercase(text) that returns uppercase text. Test it.


Class 2: Standard vs Third-Party Modules

Explanation:

  • Standard modules come with Python: math, datetime, os.

  • Third-party modules must be installed with pip: requests, numpy.

Example:

import math
print(math.sqrt(16))  # Output: 4

# Third-party example (install first with pip)
# import requests
# response = requests.get("https://example.com")
# print(response.status_code)

Classwork:

  • Use datetime module to print current date and time.

Assignment:

  • Create a small program that prints the day of the week using datetime.


Class 3: What is a Package?

Explanation:

  • A package is a folder with multiple modules.

  • It helps organize large projects.

  • Every package has a file called __init__.py.

Example:

mypackage/
    __init__.py
    module1.py
    module2.py
from mypackage import module1
module1.some_function()

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.


Class 4: File Handling – Writing to a File

Explanation:

  • File handling allows you to store and read data from a file.

  • In Django, you may read/write files for templates, static files, or media.

Example:

with open("students.txt", "w") as f:
    f.write("Ali,12\nAisha,13\nEmmanuel,14")

Classwork:

  • Write 3 favorite colors to a file called colors.txt.

Assignment:

  • Write 5 student names and ages to a file students.txt.


Class 5: File Handling – Reading a File

Explanation:

  • We can read data from files line by line or all at once.

Example:

with open("students.txt", "r") as f:
    for line in f:
        print(line)

Classwork:

  • Read colors.txt from Class 4 and print each color in uppercase.

Assignment:

  • Read students.txt and print: "Name: Ali, Age: 12" format for each line.


Class 6: Mini Project

Task:

  • Combine modules + file handling

  • Create a module student_utils.py with functions:

    • save_students(students) → saves list of students to file

    • load_students() → reads students from file

Example:

# student_utils.py
def save_students(students):
    with open("students.txt", "w") as f:
        for s in students:
            f.write(f"{s['name']},{s['age']}\n")

def load_students():
    students = []
    with open("students.txt", "r") as f:
        for line in f:
            name, age = line.strip().split(",")
            students.append({"name": name, "age": int(age)})
    return students

# main.py
import student_utils

students = [{"name":"Ali","age":12},{"name":"Aisha","age":13}]
student_utils.save_students(students)
print(student_utils.load_students())

Outcome:

  • Students understand how to organize code with modules/packages and work with files.


Class 7: Review & Practice

  • Solve exercises combining modules, packages, and file handling.

  • Discuss real-life examples of Django templates and static files.

Perfect, Raheem! Let’s finish with Week 4: Data Structures in a simple, practical way.


Week 4: Data Structures

Objective: Learn how to store and manage data — important for passing data to Django templates and working with views.


Class 1: Lists

Explanation:

  • A list is a collection of items in order.

  • You can store numbers, text, or even objects in a list.

Example:

students = ["Ali", "Aisha", "Emmanuel"]
print(students[0])  # Output: Ali

Classwork:

  • Create a list of 5 fruits and print the first and last fruit.

Assignment:

  • Create a list of 5 student names and print all names using a loop.


Class 2: Dictionaries

Explanation:

  • A dictionary stores data in key-value pairs.

  • Great for storing info like name and age.

Example:

student = {"name": "Ali", "age": 12}
print(student["name"])  # Output: Ali
print(student["age"])   # Output: 12

Classwork:

  • Create a dictionary for a book: title, author, pages. Print each value.

Assignment:

  • Create 3 student dictionaries and print their names and ages.


Class 3: Tuples

Explanation:

  • A tuple is like a list but cannot be changed.

  • Useful when data should stay the same.

Example:

books = ("Math", "English", "Science")
print(books[1])  # Output: English

Classwork:

  • Create a tuple of 5 colors and print them.

Assignment:

  • Create a tuple of 3 cities and print each city using a loop.


Class 4: Nested Data Structures

Explanation:

  • Sometimes, we combine lists and dictionaries for complex data.

  • Example: a list of students where each student is a dictionary.

Example:

students = [
    {"name": "Ali", "age": 12},
    {"name": "Aisha", "age": 13}
]

for s in students:
    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.


Class 5: Loops + Data Structures

Explanation:

  • Loops and data structures work together to process multiple items automatically.

Example:

students = [
    {"name": "Ali", "age": 12},
    {"name": "Aisha", "age": 13}
]

for s in students:
    print(s["name"].upper(), "-", s["age"])

Classwork:

  • Loop through a list of 5 fruits and print each in uppercase.

Assignment:

  • Loop through a list of dictionaries of students and print only the names.


Class 6: Mini Project

Task: Create a simple “student database”

  • Store multiple students in a list of dictionaries

  • Each student has name, age, class

  • Print all students in the format: "Ali is 12 years old in class 6"

Example:

students = [
    {"name": "Ali", "age": 12, "class": 6},
    {"name": "Aisha", "age": 13, "class": 7},
    {"name": "Emmanuel", "age": 14, "class": 8}
]

for s in students:
    print(f"{s['name']} is {s['age']} years old in class {s['class']}")

Outcome:

  • Students understand lists, dictionaries, loops, and nested structures — all needed for passing data to Django templates.


Class 7: Revision & Practice

  • Combine all data structures in exercises.

  • Example: create a program with students, teachers, and books using lists and dictionaries.


✅ After Week 4, students are ready to:

  • Use Python functions, loops, classes, modules, file handling, and data structures

  • Start Django basics: models, views, templates, and passing data


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?

  1. Fast Development – Has built-in tools, so you can make websites quickly.

  2. Secure – Protects against attacks like hacking or stealing data.

  3. Scalable – Can handle small or very big websites.

  4. Admin Panel – Gives a ready-made dashboard to manage data.

  5. Uses Python – Easy to learn and understand.

  6. Organized – Lets you reuse code and keep your project clean.

  7. 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

  1. Ask students to explain in their own words what Django is.

  2. Let them install Django on their computer.

  3. Run a project and show the welcome page in a browser.

  4. Discuss the built-in tools like admin panel and project structure.

Assignment

  1. Write a short answer: What is Django? Use simple words.

  2. List 3 reasons why Django is good for making websites.

  3. List 2 websites that use Django (examples: Instagram, Pinterest).

  4. Try creating a Django project and take a screenshot of the welcome page.

Day 2:Django Components

  1. Models – Handle data and databases.

  2. Views – Handle logic and what to show.

  3. Templates – Handle design and front-end.

  4. URLs – Connect web addresses to views.

  5. Admin – Dashboard to manage data.

  6. MVT Architecture – Structure (Model-View-Template).

  7. Middleware – Process requests and responses.

  8. Forms – Collect user input.

  9. ORM – Use Python to work with databases.

  10. 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.

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.


Python Classes Made Simple

1. What is a Class?

  • A class is like a container that holds data and actions together.

  • It tells Python what information an item has and what it can do.


2. Key Terms

  1. Object – An object is a thing created from a class.

    • Example: If Student is a class, Ali can be an object of Student.

  2. Attribute – An attribute is a piece of information about the object.

    • Example: name and age of a student.

  3. Method – A method is an action the object can do.

    • Example: say_hello() prints information about the student.

  4. self – A word used in Python to refer to the object itself.

  5. init – A special function used to set attributes when an object is created.


3. Why Use Classes?

  • To group information and actions in one place.

  • To reuse code for similar things.

  • To make your program organized and easy.


4. Simple Example: Student Class

# Create a class
class Student:
    def __init__(self, name, age):  # Attributes
        self.name = name
        self.age = age

    def say_hello(self):  # Method
        print("Hello! My name is", self.name, "and I am", self.age, "years old.")

# Create objects
student1 = Student("Ali", 12)
student2 = Student("Zara", 14)

# Use methods
student1.say_hello()
student2.say_hello()

Output:

Hello! My name is Ali and I am 12 years old.
Hello! My name is Zara and I am 14 years old.

Explanation:

  • Student → The class that has data (name, age) and action (say_hello).

  • student1, student2 → Objects made from the class.

  • self.name → The attribute name for this object.

  • say_hello() → The method that prints the info.


5. Another Simple Example: Car Class

class Car:
    def __init__(self, brand, color):  # Attributes
        self.brand = brand
        self.color = color

    def show_car(self):  # Method
        print("This car is a", self.color, self.brand)

# Create object
my_car = Car("Toyota", "Red")
my_car.show_car()

Output:

This car is a Red Toyota

Classwork

  1. Make a class Teacher with name and subject.

  2. Make a method introduce() that prints: "I am [name] and I teach [subject]".

  3. Create 2 teacher objects and call introduce().


Assignment

  1. Make a class Book with title and author.

  2. Make a method show() that prints: "Book: [title] by [author]".

  3. Create 3 book objects and call show() for each.

  4. Bonus: Add an attribute pages and include it in show().

Day 4:

field types, database basics, migrations.

Got it, Raheem! Let’s explain Field Types, Database Basics, and Migrations in very simple English, step by step, for your students.


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 modeltable

  • Each objectrow 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:

  1. Create migration (tell Django about changes):

python manage.py makemigrations
  1. Apply migration (update database):

python manage.py migrate

Example Workflow:

  • Create model Studentmakemigrationsmigrate → Table created in database

  • Add a new field grademakemigrationsmigrate → Table updates


Classwork Example

  1. Create a model Teacher with:

    • name (CharField)

    • subject (CharField)

    • age (IntegerField)

    • hire_date (DateField)

    • is_active (BooleanField)

  2. Make migrations and migrate.

  3. Check the table in the database.


Assignment Example

  1. Create a model Book with:

    • title (CharField)

    • author (CharField)

    • pages (IntegerField)

    • published_date (DateField)

    • available (BooleanField)

  2. Make migrations and migrate.

  3. Add 3 book objects using Django admin.

  4. 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

  1. What is a field type in Django? Give two examples.

  2. What is a database? What is a table in a database?

  3. What is an object in Django?

  4. What is a migration and why is it important?

  5. 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:

  1. Create the model in models.py.

  2. Make migrations and migrate.

  3. Add 2 student objects using Django admin.

  4. 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:

  1. Create the model in models.py.

  2. Make migrations and migrate.

  3. Add 3 book objects using Django admin.

  4. 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.

  • 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)

  1. You create a model → Python class in models.py.

  2. Django reads the model and creates a database table (columns = fields).

  3. You create objects → Django inserts rows in the table.

  4. You query objects → Django fetches rows from the table.

  5. You update objects → Django updates rows in the table.

  6. 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

  1. Create a model Teacher with fields:

    • name, subject, age, hire_date, is_active

  2. Make migrations and migrate.

  3. Add 2 teacher objects.

  4. Retrieve all teachers and print their names.

  5. Update one teacher’s age.

  6. Delete one teacher.

Assignment Example

  1. Create a model Book with fields:

    • title, author, pages, published_date, available

  2. Make migrations and migrate.

  3. Add 3 book objects.

  4. Retrieve all books.

  5. Update the number of pages for one book.

  6. Delete one book.

Day 2: Locate the Database File

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)

  1. Download DB Browser for SQLite (free).

  2. Open db.sqlite3 in the app.

  3. You will see all tables Django created.

    • Example: myapp_student, myapp_teacher

  4. Click on a table to see its rows and columns (your data).


B. Using Django Shell

  1. Open Django shell in terminal:

python manage.py shell
  1. Import your model and see data:

from myapp.models import Student
Student.objects.all()   # Shows all records in Student table
  1. ✅ Each object corresponds to a row in the table.


C. Using Django Admin Panel

  1. Register your model in admin.py:

from django.contrib import admin
from .models import Student

admin.site.register(Student)
  1. Run the server:

python manage.py runserver
  1. Open http://127.0.0.1:8000/admin/ and login.

  2. 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

  1. Create a model Teacher with name and subject.

  2. Make migrations and migrate.

  3. Open db.sqlite3 in DB Browser.

  4. Add a teacher in admin and see it in the table.


Assignment Example

  1. Create a model Book with title, author, pages.

  2. Make migrations and migrate.

  3. Open db.sqlite3 and locate the Book table.

  4. Add 3 book entries in admin and check the table.

Week 3: How to use templates

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

  1. 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})
  1. 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'),
]
  1. 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

  1. User visits a URL (e.g., /students/).

  2. Django runs the view (student_list).

  3. View gets data from model (Student.objects.all()).

  4. View sends data to template.

  5. Template shows data as HTML page.


7. Classwork Example

  1. Create a model Teacher with name and subject.

  2. Create a view teacher_list that gets all teachers.

  3. Create a template teacher_list.html to show all teachers.

  4. Connect URL /teachers/ to the view.

  5. Open browser and check the page.


8. Assignment Example

  1. Create a model Book with fields title, author, pages.

  2. Create a view book_list to get all books.

  3. Create a template book_list.html that shows all books.

  4. Add a URL /books/ to connect the view.

  5. Test in the browser.

  6. Bonus: Add a loop to highlight books with more than 200 pages using {% if %} tag.


Week 4: URLs.

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

  1. User visits a URL in the browser.

  2. Django matches the URL to a path in urls.py.

  3. Django runs the view connected to that URL.

  4. 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

  1. Create a view teacher_list that shows all teachers.

  2. Create a URL /teachers/ that runs the view.

  3. Test in the browser and see the list of teachers.


8. Assignment Example

  1. Create a view book_list that shows all books.

  2. Create a URL /books/ that runs the view.

  3. Bonus: Create another URL /books/<int:id>/ to show a single book’s details.

  4. Test both URLs in the browser.

Month 2:

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

  1. Register your model in admin.py:

from django.contrib import admin
from .models import Student

admin.site.register(Student)
  1. Run the server:

python manage.py runserver
  1. Go to http://127.0.0.1:8000/admin/ and login.

  2. 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

  1. Register Student model in admin and add 2 students.

  2. Create a form for students to submit data.

  3. Use ORM to retrieve and update a student.

  4. Check CSRF token in template for security.


Assignment Example

  1. Create Book model and register in admin.

  2. Make a form to add books.

  3. Use ORM to get all books and filter available books.

  4. Add CSRF token to the form template.

  5. 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.





0 comments:

Post a Comment

 

BEST COMPUTER GUIDE Written by Abigail Odenigbo, Published @ 2014 by NOBIGDEAL(Ipietoon)