WEEKLY DJANGO TRAINING GUIDE
Week
1: Python Fundamentals (Foundation for Django)
Topics:
- Variables, data types, operators
- If/else, loops
- Functions
- Lists, tuples, dictionaries
Example:
#
Example: Check if a number is even or odd
num
= 7
if
num % 2 == 0:
print("Even")
else:
print("Odd")
Assessment Assignment:
👉 Write a Python program that takes 5 student scores, stores them in a
list, and prints the average score.
Solution:
scores
= [80, 70, 65, 90, 85]
average
= sum(scores) / len(scores)
print("Average
Score:", average)
Week
2: Web Basics (HTML, CSS, JS)
Topics:
- HTML structure, forms, tables
- CSS basics
- Simple JavaScript
Example: (HTML Form)
<!DOCTYPE
html>
<html>
<body>
<h2>Student Registration</h2>
<form>
Name: <input type="text" name="name"><br>
Age: <input type="number" name="age"><br>
<button type="submit">Register</button>
</form>
</body>
</html>
Assessment Assignment:
👉 Create a webpage with a form to collect name, email, and password.
Solution (HTML):
<!DOCTYPE
html>
<html>
<body>
<form>
Name: <input type="text"><br>
Email: <input type="email"><br>
Password: <input type="password"><br>
<button type="submit">Submit</button>
</form>
</body>
</html>
Week
3: Django Basics
Topics:
- Install Django (pip
install django)
- Create a project & app
- URL routing
- Views & Templates
Example:
#
views.py
from
django.http import HttpResponse
def
home(request):
return HttpResponse("Welcome to My
First Django App")
Assessment Assignment:
👉 Create a Django project called mysite with an app blog. Add a homepage that displays “Hello World Blog”.
Solution:
#
blog/views.py
from
django.http import HttpResponse
def
index(request):
return HttpResponse("Hello World
Blog")
#
mysite/urls.py
from
django.contrib import admin
from
django.urls import path
from
blog import views
urlpatterns
= [
path('admin/', admin.site.urls),
path('', views.index),
]
Week
4: Django Models & Database (SQLite)
Topics:
- Models (models.py)
- Migrations
- Django ORM (create, read, update, delete)
- Admin panel
Example:
#
blog/models.py
from
django.db import models
class
Student(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
Assessment Assignment:
👉 Create a model for a Book with fields: title, author,
year. Add at least 2 books to the
database.
Solution:
#
models.py
class
Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=100)
year = models.IntegerField()
#
Using Django shell
from
blog.models import Book
Book.objects.create(title="Django
for Beginners", author="William", year=2020)
Book.objects.create(title="Python
Crash Course", author="Eric", year=2019)
Week
5: User Authentication
Topics:
- User login/logout
- Registration form
- Django authentication system
Example:
from
django.contrib.auth.models import User
#
Create user
user
= User.objects.create_user(username="john", password="mypassword")
Assessment Assignment:
👉 Create a signup page where a new user can register with a username
and password.
Solution (simplified):
#
views.py
from
django.contrib.auth.models import User
from
django.http import HttpResponse
def
signup(request):
user = User.objects.create_user("student1",
password="12345")
return HttpResponse("User
Created")
Week
6: Django + MySQL
Topics:
- Install MySQL server
- Connect Django to MySQL (mysqlclient)
- Update settings.py with MySQL config
- CRUD operations with ORM
Example (settings.py):
DATABASES
= {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'school_db',
'USER': 'root',
'PASSWORD': 'password',
'HOST': 'localhost',
'PORT': '3306',
}
}
Assessment Assignment:
👉 Create a Library model with fields: book_name, student_name, borrow_date. Save it in MySQL.
Solution:
#
models.py
class
Library(models.Model):
book_name = models.CharField(max_length=100)
student_name = models.CharField(max_length=100)
borrow_date = models.DateField()
#
Django shell
from
blog.models import Library
Library.objects.create(book_name="Maths
Book", student_name="Alice", borrow_date="2025-01-20")
Week
7: Final Project
👉 Build a Student
Management System with MySQL:
- Students can register/login
- Admin can add/update/delete students
- Students can see their details
Week
1 — Python fundamentals
Recommended time: 1–2 hours/day.
Mon — Variables & Types
- Learn: numbers, strings, booleans.
- Try: assign variables, print, string methods (.upper(),
.split()).
Tue — Control flow
- Learn: if/elif/else, for and while loops, break/continue.
- Try: loop through a list and print only even numbers.
Wed — Functions & modules
- Learn: define functions, return values, import modules.
- Try: write a function avg(list_of_numbers).
Thu — Data structures & file I/O
- Learn: lists, tuples, dicts, sets; open/read/write
files.
- Try: store student records in a list of dicts and write
to students.txt.
Fri
— Assessment (Task + Solution)
Task:
Write a Python script that:
- Reads 5 student scores (you can hardcode them into a
list).
- Prints the average, highest, lowest score.
- Prints how many students passed (pass = score ≥ 50).
Solution:
#
week1_assessment.py
scores
= [80, 70, 65, 90, 45] # hardcoded for
the test
average
= sum(scores) / len(scores)
highest
= max(scores)
lowest
= min(scores)
passes
= sum(1 for s in scores if s >= 50)
print("Scores:",
scores)
print("Average:",
average)
print("Highest:",
highest)
print("Lowest:",
lowest)
print("Number
passed:", passes)
Explanation: Uses built-in functions sum, max,
min and a generator to count passes.
Sat — Practice
- Small project: CLI to add/remove student scores and
save to file.
Sun — Review
- Re-run Friday script, tweak scores, explain each line
out loud.
Week
2 — Web basics: HTML / CSS / JS
Recommended time: 1–2 hours/day.
Mon — HTML basics
- Tags: <!DOCTYPE>, <html>, <head>, <body>, headings, paragraphs, lists, links, images.
Tue — Forms & tables
- Learn form elements: <form>, <input>, <select>, <textarea>.
- Try: build a student registration form.
Wed — CSS basics
- Selectors, classes/ids, box model, simple layout.
- Try: style your registration form.
Thu — Basic JavaScript
- DOM basics, form validation, addEventListener,
simple functions.
Fri
— Assessment (Task + Solution)
Task:
Create an HTML page register.html with a form (name, email, password) and a small inline
JavaScript that prevents submission if password < 6 chars and shows an
alert.
Solution (single file):
<!--
week2_assessment.html -->
<!DOCTYPE
html>
<html>
<head>
<meta charset="utf-8" />
<title>Register</title>
<style>
body { font-family: Arial, sans-serif; margin:
30px; }
label { display:block; margin-top:8px; }
</style>
</head>
<body>
<h2>Register</h2>
<form id="regForm">
<label>Name: <input type="text"
id="name" required></label>
<label>Email: <input type="email"
id="email" required></label>
<label>Password: <input type="password"
id="password" required></label>
<button type="submit">Submit</button>
</form>
<script>
const form = document.getElementById('regForm');
form.addEventListener('submit', function(e)
{
const pw = document.getElementById('password').value;
if
(pw.length < 6) {
e.preventDefault();
alert('Password must be at least 6
characters.');
}
});
</script>
</body>
</html>
Explanation: Form has client-side validation; prevents submit if rule
fails.
Sat — Practice
- Style the form with CSS and add client-side email
format hints.
Sun — Review
- Test in mobile view, tweak UI.
Week
3 — Django basics: project & app
Recommended time: 1–2 hours/day. Use
a virtual environment.
Mon — Setup
- Create venv, activate, install Django:
·
python -m venv venv
·
# Windows: venv\Scripts\activate
·
# Linux/Mac: source
venv/bin/activate
·
pip install django
- django-admin startproject mysite
Tue — Start an app
- python manage.py startapp blog
- Understand settings.py, urls.py, app in INSTALLED_APPS.
Wed — Views & URLs
- Create view functions in blog/views.py and map in mysite/urls.py.
Thu — Templates & static files
- Create templates/ and static/ folders and use render().
Fri
— Assessment (Task + Solution)
Task:
Create a Django project mysite
and app blog.
Add a homepage that displays “Hello World Blog”.
Solution (core files):
blog/views.py
from
django.shortcuts import HttpResponse
def
index(request):
return HttpResponse("Hello World
Blog")
mysite/urls.py
from
django.contrib import admin
from
django.urls import path
from
blog.views import index
urlpatterns
= [
path('admin/', admin.site.urls),
path('', index, name='home'),
]
Commands to run:
python
manage.py migrate
python
manage.py runserver
#
open http://127.0.0.1:8000/ to see "Hello World Blog"
Explanation: Minimal view returning HttpResponse and route to root.
Sat — Practice
- Replace HttpResponse with a template index.html
that uses CSS.
Sun — Review
- Try adding a second page and link it from the homepage.
Week
4 — Models & Database (SQLite)
Recommended time: 1–2 hours/day.
Mon — Models
- Create models in blog/models.py. Example: Book model.
Tue — Migrations & admin
- makemigrations,
migrate,
register models in blog/admin.py.
Wed — Django ORM: CRUD
- Use Django shell to create/read/update/delete (python manage.py shell).
Thu — Views + Templates with DB
- List objects in a view and show in a template.
Fri
— Assessment (Task + Solution)
Task:
Add a Book
model with fields title,
author, year. Create two books and show how to query all books.
Solution:
blog/models.py
from
django.db import models
class
Book(models.Model):
title = models.CharField(max_length=200)
author = models.CharField(max_length=100)
year = models.IntegerField()
def __str__(self):
return f"{self.title} by {self.author}
({self.year})"
Run:
python
manage.py makemigrations
python
manage.py migrate
python
manage.py createsuperuser # optional to
use admin
Create in shell:
#
python manage.py shell
from
blog.models import Book
Book.objects.create(title="Django
for Beginners", author="William", year=2020)
Book.objects.create(title="Python
Crash Course", author="Eric", year=2019)
#
Query
books
= Book.objects.all()
for
b in books:
print(b)
Explanation: Basic model, migrations, object creation and query.
Sat — Practice
- Build a page that lists books (template + view).
Sun — Review
- Add search/filter by author using .filter(author__icontains='will').
Week
5 — Authentication
Recommended time: 1–2 hours/day.
Mon — Django auth basics
- Built-in User model, login/logout functions, auth urls.
Tue — Registration
- Use UserCreationForm to create a signup page.
Wed — Protecting views
- Use @login_required and LoginRequiredMixin for CBVs.
Thu — Passwords & profiles
- Change password, add a Profile model (OneToOne to User) if needed.
Fri
— Assessment (Task + Solution)
Task:
Create a registration view using Django’s UserCreationForm and show the view, url, and minimal template.
Solution:
blog/forms.py (optional, but simple use built-in form)
from
django import forms
from
django.contrib.auth.forms import UserCreationForm
from
django.contrib.auth.models import User
class
SignUpForm(UserCreationForm):
email = forms.EmailField(required=True)
class Meta:
model = User
fields = ("username", "email",
"password1", "password2")
blog/views.py
from
django.shortcuts import render, redirect
from
.forms import SignUpForm
def
signup(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
form.save()
return redirect('login') # assumes you have login view
else:
form = SignUpForm()
return render(request, 'signup.html', {'form':
form})
mysite/urls.py (add)
from
django.urls import path, include
from
blog import views as blog_views
urlpatterns
= [
path('admin/', admin.site.urls),
path('signup/', blog_views.signup, name='signup'),
path('accounts/', include('django.contrib.auth.urls')), # login/logout
]
templates/signup.html
<h2>Sign
up</h2>
<form
method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Register</button>
</form>
Explanation: Uses Django’s form to create users and django.contrib.auth.urls for login/logout views.
Sat — Practice
- Add login/logout links, test signup and login, protect
a view with @login_required.
Sun — Review
- Try adding user profile fields and display them.
Week
6 — Django + MySQL
Recommended time: 1–2 hours/day.
(You must install MySQL server separately.)
Mon — Install MySQL + driver
- Option A (recommended if system libs available): pip install mysqlclient
(may require libmysqlclient).
- Option B (pure Python): pip
install pymysql and add to mysite/__init__.py:
·
import pymysql
·
pymysql.install_as_MySQLdb()
Tue — Configure settings.py
- Replace DATABASES['default'] with MySQL settings:
DATABASES
= {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'school_db',
'USER': 'root',
'PASSWORD': 'your_password',
'HOST': '127.0.0.1',
'PORT': '3306',
}
}
Wed — Migrate & test
- python manage.py migrate
(creates tables in MySQL)
- python manage.py runserver and test.
Thu — ORM with MySQL
- Use same models — they work with MySQL through ORM.
Fri
— Assessment (Task + Solution)
Task:
Show how to configure Django to use MySQL and create a Library model (book_name, student_name, borrow_date) then create a record.
Solution:
- Install driver: either mysqlclient or pymysql (see Mon).
- settings.py
(example):
DATABASES
= {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'school_db',
'USER': 'root',
'PASSWORD': 'mypassword',
'HOST':
'127.0.0.1',
'PORT': '3306',
}
}
- blog/models.py
from
django.db import models
class
Library(models.Model):
book_name = models.CharField(max_length=200)
student_name = models.CharField(max_length=100)
borrow_date = models.DateField()
def __str__(self):
return f"{self.book_name} borrowed
by {self.student_name}"
- Run migrations:
python
manage.py makemigrations
python
manage.py migrate
- Create record in shell:
from
blog.models import Library
Library.objects.create(book_name="Maths
Book", student_name="Alice", borrow_date="2025-01-20")
Explanation: Django ORM handles SQL for you; MySQL stores the data.
Sat — Practice
- Build a simple page to list borrow records; allow
adding via ModelForm (see Week 7).
Sun — Review
- Inspect the MySQL database with a client (MySQL
Workbench / command line) to confirm rows.
Week
7 — Forms, CBVs, REST intro, Deployment (final project week)
Recommended time: 1–2 hours/day.
Mon — Django Forms & ModelForm
- Learn forms.Form and forms.ModelForm.
- Try: create a BookForm to add books.
Tue — Class-Based Views (CBV)
- Learn ListView, DetailView, CreateView, UpdateView, DeleteView.
Wed — Django REST Framework (intro)
- pip install djangorestframework, build a simple API view for Book.
Thu — Deployment basics
- Collect static, allowed hosts, simple tips for
deploying to services (Heroku/ PythonAnywhere / VPS). (Follow up later for
exact steps.)
Fri
— Assessment (Task + Solution)
Task:
Create a ModelForm for the Book model and a view to create a book (show form, validate,
save). Provide view, template, and url.
Solution:
blog/forms.py
from
django import forms
from
.models import Book
Week 1: Python Fundamentals
Day
1 (Monday): Variables and Data Types
Lesson:
- Variables are names that store values.
- Common data types:
- int
(numbers)
- float
(decimal numbers)
- str
(text)
- bool
(True/False)
Examples:
name
= "Raheem"
age
= 25
height
= 5.9
is_student
= True
print("Name:",
name)
print("Age:",
age)
print("Height:",
height)
print("Student:",
is_student)
Assignment:
👉 Create 4 variables: your name, age, city, and whether you like Python
(True/False). Print
them out.
Day
2 (Tuesday): If/Else & Loops
Lesson:
- if/else
allows decision-making.
- Loops (for and while) repeat actions.
Examples:
#
Example 1: if/else
score
= 70
if
score >= 50:
print("Pass")
else:
print("Fail")
#
Example 2: loop
for
i in range(1, 6):
print("Number:", i)
Assignment:
👉 Write a loop that prints numbers from 1 to 20, but only prints the
even ones.
Day
3 (Wednesday): Functions
Lesson:
- Functions group code for reuse.
- Use def to define, return to give a result.
Examples:
def
greet(name):
return "Hello " + name
print(greet("Raheem"))
print(greet("Ada"))
Assignment:
👉 Write a function square(num) that returns the square of any number.
Day
4 (Thursday): Lists & Dictionaries
Lesson:
- Lists hold multiple items in order.
- Dictionaries hold key–value pairs.
Examples:
#
List
scores
= [80, 60, 95]
print("First
score:", scores[0])
#
Dictionary
student
= {"name": "Raheem", "age": 25, "city":
"Abuja"}
print(student["name"],
"is", student["age"], "years old")
Assignment:
👉 Create a list of 5 fruits and a dictionary for your own details
(name, school, course). Print them out.
Day
5 (Friday): Assessment
Task:
Write a program that stores 5 student scores in a list.
- Print the average score
- Print the highest score
- Print the lowest score
- Print how many students passed (≥50)
Solution:
scores
= [80, 70, 65, 90, 45]
average
= sum(scores) / len(scores)
highest
= max(scores)
lowest
= min(scores)
passes
= sum(1 for s in scores if s >= 50)
print("Scores:",
scores)
print("Average:",
average)
print("Highest:",
highest)
print("Lowest:",
lowest)
print("Number
passed:", passes)
Output:
Scores:
[80, 70, 65, 90, 45]
Average:
70.0
Highest:
90
Lowest:
45
Number
passed: 4
Week 2: Web Basics for Django (HTML, CSS, JS)
Day
1 (Monday): Learning HTML Basics
What we’re doing:
- Learning the basic structure of a webpage so that later
Django templates can render it.
- HTML tags: <html>, <head>, <body>, headings <h1>…<h6>, paragraph <p>, links <a>, and images <img>.
Example:
<!DOCTYPE
html>
<html>
<head>
<title>My First Webpage</title>
</head>
<body>
<h1>Welcome to My Webpage</h1>
<p>This is a paragraph explaining
something about me.</p>
<a href="https://www.google.com">Go
to Google</a>
<img src="https://via.placeholder.com/150"
alt="Sample Image">
</body>
</html>
What we’re teaching:
- <h1>
creates a heading
- <p>
creates a paragraph
- <a>
creates a clickable link
- <img>
inserts an image
Assignment:
👉 Create your own webpage that introduces yourself. Include:
- Your name as a heading
- A short paragraph about yourself
- One image (can be any link)
- One link to a website you like
Day
2 (Tuesday): HTML Forms
What we’re doing:
- Learning how users can input data (like
username/password) which later Django can handle.
- Tags: <form>, <input>, <label>, <button>.
Example:
<form>
<label>Name: <input type="text"
name="name"></label><br>
<label>Email: <input type="email"
name="email"></label><br>
<label>Password: <input type="password"
name="password"></label><br>
<button type="submit">Register</button>
</form>
What we’re teaching:
- type="text"
→ text input
- type="email"
→ email input
- type="password"
→ hides typed characters
- <button>
→ submits the form
Assignment:
👉 Make a registration form with fields: Name, Age, Email, Password,
City.
Day
3 (Wednesday): CSS Basics
What we’re doing:
- Learning how to style our webpage and forms.
- CSS can be inline, internal, or external.
We’ll use internal CSS for simplicity.
Example:
<head>
<style>
body { font-family: Arial; background-color:
#f0f0f0; }
h1 { color: #2a9d8f; }
p { color: #264653; }
input { padding: 5px; margin: 5px 0; }
button { background-color: #e76f51; color:
white; padding: 5px 10px; }
</style>
</head>
What we’re teaching:
- How to change font, colors, spacing,
and button styles.
Assignment:
👉 Add internal CSS to your registration form to make it look nicer
(background color, styled button, styled text).
Day
4 (Thursday): JavaScript Basics
What we’re doing:
- Adding simple form validation using JavaScript.
- JavaScript runs in the browser to check inputs before
submitting.
Example:
<script>
const form = document.querySelector('form');
form.addEventListener('submit', function(e) {
const pw = document.querySelector('input[type="password"]').value;
if(pw.length < 6) {
e.preventDefault(); // prevent submission
alert('Password must be at least 6
characters');
}
});
</script>
What we’re teaching:
- addEventListener('submit', …) → runs code when form is submitted
- preventDefault()
→ stops form from submitting if rules fail
- alert() →
shows a message
Assignment:
👉 Add JS validation to your registration form:
- Password ≥ 6 characters
- Age ≥ 10
Day
5 (Friday): Assessment
What we’re doing:
- Testing if you understood HTML, CSS, and JS together.
Task:
- Create a webpage register.html
- Form fields: Name, Email, Password, Age
- Style it with internal CSS
- Add JS validation: password ≥ 6 chars, age ≥ 10
Solution:
<!DOCTYPE
html>
<html>
<head>
<meta charset="utf-8">
<title>Register</title>
<style>
body { font-family: Arial; background-color:
#eef2f3; padding: 20px; }
h2 { color: #2a9d8f; }
label { display:block; margin:10px 0 5px; }
input { padding: 5px; width: 200px; }
button { background-color: #e76f51; color:
white; padding: 5px 15px; margin-top: 10px; }
</style>
</head>
<body>
<h2>Register</h2>
<form id="regForm">
<label>Name: <input type="text"
id="name" required></label>
<label>Email: <input type="email"
id="email" required></label>
<label>Password: <input type="password"
id="password" required></label>
<label>Age: <input type="number"
id="age" required></label>
<button type="submit">Submit</button>
</form>
<script>
const form = document.getElementById('regForm');
form.addEventListener('submit', function(e){
const pw = document.getElementById('password').value;
const age = parseInt(document.getElementById('age').value);
if(pw.length < 6){
e.preventDefault();
alert('Password must be at least 6
characters');
}
if(age < 10){
e.preventDefault();
alert('Age must be at least 10');
}
});
</script>
</body>
</html>
What you learned this week:
- Basic HTML tags
- Forms to get user input
- Internal CSS styling
- Simple JavaScript validation
Week 3: Django Basics
Prerequisite: Python basics and basic HTML/CSS from Week 1–2.
Day
1 (Monday): Install Django and Create a Project
What we’re doing:
- Installing Django and creating our first project so we
can start building web apps.
Steps:
- Open terminal/command prompt.
- Create a virtual environment (good practice):
python
-m venv venv
#
Windows: venv\Scripts\activate
#
Linux/Mac: source venv/bin/activate
- Install Django:
pip
install django
- Create Django project called mysite:
django-admin
startproject mysite
- Run the server to check:
cd
mysite
python
manage.py runserver
- Open http://127.0.0.1:8000/ in browser → You should see “The install worked
successfully” page.
Assignment:
👉 Install Django, create a project mysite, and run the server. Take a screenshot of the welcome page.
Day
2 (Tuesday): Create a Django App
What we’re doing:
- Django projects are divided into apps.
- We’ll create a blog app to add features later.
Steps:
- Create app:
python
manage.py startapp blog
- Add app to INSTALLED_APPS in mysite/settings.py:
INSTALLED_APPS
= [
'django.contrib.admin',
'django.contrib.auth',
...
'blog',
]
Assignment:
👉 Create an app called blog and confirm it is added to INSTALLED_APPS.
Day
3 (Wednesday): Views and URL Routing
What we’re doing:
- Views handle requests and return responses.
- URLs map web addresses to views.
Example:
blog/views.py
from
django.http import HttpResponse
def
home(request):
return HttpResponse("Welcome to My
Blog Home")
mysite/urls.py
from
django.contrib import admin
from
django.urls import path
from
blog.views import home
urlpatterns
= [
path('admin/', admin.site.urls),
path('', home, name='home'),
]
- Open browser http://127.0.0.1:8000/ → Should display “Welcome to My Blog Home”
Assignment:
👉 Create a new view about that returns “This is the About Page”. Add it to
URLs: /about/.
Day
4 (Thursday): Templates and Static Files
What we’re doing:
- Templates are HTML files rendered by Django.
- Static files are CSS, JS, and images.
Steps:
- Create a folder templates inside blog.
- Create home.html inside templates:
<!DOCTYPE
html>
<html>
<head>
<title>Blog Home</title>
</head>
<body>
<h1>Welcome to My Blog</h1>
<p>This is the homepage rendered with
Django templates.</p>
</body>
</html>
- Update views.py to render template:
from
django.shortcuts import render
def
home(request):
return render(request, 'home.html')
- Run server → homepage now uses your HTML template.
Assignment:
👉 Create about.html template with heading “About My Blog” and paragraph
describing your blog. Update about view to render it.
Day
5 (Friday): Assessment
What we’re doing:
- Friday test to check if you understand project
creation, apps, views, URLs, and templates.
Task:
- Create a project mysite
- Create app blog
- Create 2 pages:
- / →
homepage: “Welcome to My Blog”
- /about/
→ about page: “This is the About Page”
- Use templates, not HttpResponse.
Solution:
blog/views.py
from
django.shortcuts import render
def
home(request):
return render(request, 'home.html')
def
about(request):
return render(request, 'about.html')
mysite/urls.py
from
django.contrib import admin
from
django.urls import path
from
blog import views
urlpatterns
= [
path('admin/', admin.site.urls),
path('', views.home, name='home'),
path('about/', views.about, name='about'),
]
blog/templates/home.html
<!DOCTYPE
html>
<html>
<head><title>Home</title></head>
<body>
<h1>Welcome
to My Blog</h1>
<p>This
is the homepage rendered with Django templates.</p>
</body>
</html>
blog/templates/about.html
<!DOCTYPE
html>
<html>
<head><title>About</title></head>
<body>
<h1>About
My Blog</h1>
<p>This
is the About Page.</p>
</body>
</html>
Run python
manage.py runserver → check / and /about/.
What
you learned this week:
- Install Django and create a project
- Create apps
- Create views and map URLs
- Use templates for HTML pages
- Prepare static folder for CSS/JS later
Week 4: Django Models & Database (SQLite)
Prerequisite: Django basics from Week 3 (project, app, templates, views).
Day
1 (Monday): Introduction to Models
What we’re doing:
- Learning what models are: models are Python classes
that represent database tables.
- Django uses ORM (Object Relational Mapping) to
interact with databases.
- By default, Django uses SQLite.
Example:
blog/models.py
from
django.db import models
class
Student(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
city = models.CharField(max_length=100)
def __str__(self):
return self.name
What we’re teaching:
- models.Model
→ tells Django this is a database table
- CharField
→ text field with max length
- IntegerField
→ integer number field
- __str__ →
how object appears in admin
Assignment:
👉 Create a Book
model with fields: title
(text), author
(text), year
(integer).
Day
2 (Tuesday): Migrations & Admin
What we’re doing:
- Learning to apply model changes to database
using migrations.
- Register models in admin panel to manage data
via web.
Steps:
- Make migrations:
python
manage.py makemigrations
python
manage.py migrate
- Register model in blog/admin.py:
from
django.contrib import admin
from
.models import Student
admin.site.register(Student)
- Create superuser:
python
manage.py createsuperuser
#
Enter username, email, password
- Run server → go to /admin/ → login → see Students table
Assignment:
👉 Register the Book
model in admin panel and create 2 book entries.
Day
3 (Wednesday): Django ORM (CRUD Operations)
What we’re doing:
- Learn CRUD: Create, Read, Update, Delete using
Django ORM.
Example:
from
blog.models import Student
#
Create
s1
= Student.objects.create(name="Alice", age=15, city="Abuja")
#
Read
students
= Student.objects.all()
for
s in students:
print(s.name, s.age)
#
Update
s1.age
= 16
s1.save()
#
Delete
s1.delete()
Assignment:
👉 Using the Book
model:
- Create 2 books in Django shell
- List all books
- Update the year of one book
- Delete one book
Day
4 (Thursday): Views & Templates with Models
What we’re doing:
- Learn to display database data in templates.
Example:
blog/views.py
from
django.shortcuts import render
from
.models import Student
def
student_list(request):
students = Student.objects.all()
return render(request, 'student_list.html',
{'students': students})
blog/templates/student_list.html
<h1>Students
List</h1>
<ul>
{%
for student in students %}
<li>{{ student.name }} - {{
student.age }} years old - {{ student.city }}</li>
{%
endfor %}
</ul>
mysite/urls.py (add path)
from
blog.views import student_list
urlpatterns
+= [path('students/', student_list, name='student_list')]
- Run server → /students/ → see all students
Assignment:
👉 Create a view book_list to display all books in a template book_list.html.
Day
5 (Friday): Assessment
What we’re doing:
- Friday test: Check if you understand models,
migrations, ORM, admin, and displaying data.
Task:
- Create a Book model (title, author, year)
- Make migrations and migrate
- Register Book in admin panel
- Create at least 2 books in admin
- Create a view and template to display all books
Solution:
blog/models.py
from
django.db import models
class
Book(models.Model):
title = models.CharField(max_length=200)
author = models.CharField(max_length=100)
year = models.IntegerField()
def __str__(self):
return self.title
blog/admin.py
from
django.contrib import admin
from
.models import Book
admin.site.register(Book)
blog/views.py
from
django.shortcuts import render
from
.models import Book
def
book_list(request):
books = Book.objects.all()
return render(request, 'book_list.html', {'books':
books})
blog/templates/book_list.html
<h1>Books
List</h1>
<ul>
{%
for book in books %}
<li>{{ book.title }} by {{
book.author }} ({{ book.year }})</li>
{%
endfor %}
</ul>
mysite/urls.py
from
blog.views import book_list
urlpatterns
+= [path('books/', book_list, name='book_list')]
✅ Run server → visit /books/ → see the books
What
you learned this week:
- Create models (tables) in Django
- Apply migrations to database
- Use admin panel to manage data
- Use ORM for CRUD operations
- Display database data in templates
Week 5: Django User Authentication
Prerequisite: Django basics and models from previous weeks.
Day
1 (Monday): Django Authentication Basics
What we’re doing:
- Learning how to use Django’s built-in User model
for authentication.
- Features: login, logout, and built-in user management.
Example:
#
In views.py
from
django.shortcuts import render
from
django.contrib.auth.decorators import login_required
@login_required
def
dashboard(request):
return render(request, 'dashboard.html')
What we’re teaching:
- login_required
→ prevents access to a page if user is not logged in.
- Default login URL: /accounts/login/ (we’ll create this next).
Assignment:
👉 Create a dashboard.html template with a heading “User Dashboard” and
decorate view with @login_required. Test by trying to access page without logging in.
Day
2 (Tuesday): User Registration (Signup)
What we’re doing:
- Create a signup page using Django’s built-in UserCreationForm.
Example:
blog/forms.py
from
django import forms
from
django.contrib.auth.forms import UserCreationForm
from
django.contrib.auth.models import User
class
SignUpForm(UserCreationForm):
email = forms.EmailField(required=True)
class Meta:
model = User
fields = ('username', 'email', 'password1',
'password2')
blog/views.py
from
django.shortcuts import render, redirect
from
.forms import SignUpForm
def
signup(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
form.save()
return redirect('login')
else:
form = SignUpForm()
return render(request, 'signup.html', {'form':
form})
templates/signup.html
<h2>Sign
Up</h2>
<form
method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Register</button>
</form>
urls.py
from
blog import views
urlpatterns
+= [path('signup/', views.signup, name='signup')]
Assignment:
👉 Create signup page using UserCreationForm. After successful signup, redirect user to login page.
Day
3 (Wednesday): Login and Logout
What we’re doing:
- Use Django’s built-in login/logout views.
Steps:
- Include auth URLs in urls.py:
from
django.urls import path, include
urlpatterns
+= [
path('accounts/', include('django.contrib.auth.urls')),
]
- Default login template: registration/login.html (create template folder registration)
registration/login.html
<h2>Login</h2>
<form
method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Login</button>
</form>
- Access: /accounts/login/ → login page
- Logout: /accounts/logout/ → logs user out
Assignment:
👉 Create login page. Test login and logout flow. Redirect logged-in
users to dashboard (@login_required).
Day
4 (Thursday): Protecting Views
What we’re doing:
- Learn how to protect pages so only logged-in users can
access.
Example:
views.py
from
django.contrib.auth.decorators import login_required
@login_required
def
profile(request):
return render(request, 'profile.html', {'user':
request.user})
profile.html
<h2>User
Profile</h2>
<p>Username:
{{ user.username }}</p>
<p>Email:
{{ user.email }}</p>
- Visiting /profile/ without login → redirected to login page
Assignment:
👉 Create a profile page protected with @login_required showing username and email.
Day
5 (Friday): Assessment
What we’re doing:
- Friday assessment to test signup, login, logout, and
protected pages.
Task:
- Create a signup page
- Create login and logout
- Create a protected dashboard page
- Test full flow: signup → login → access dashboard →
logout
Solution:
blog/forms.py
from
django import forms
from
django.contrib.auth.forms import UserCreationForm
from
django.contrib.auth.models import User
class
SignUpForm(UserCreationForm):
email = forms.EmailField(required=True)
class Meta:
model = User
fields = ('username', 'email', 'password1',
'password2')
blog/views.py
from
django.shortcuts import render, redirect
from
django.contrib.auth.decorators import login_required
from
.forms import SignUpForm
def
signup(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
form.save()
return redirect('login')
else:
form = SignUpForm()
return render(request, 'signup.html', {'form':
form})
@login_required
def
dashboard(request):
return render(request, 'dashboard.html')
urls.py
from
blog import views
from
django.urls import path, include
urlpatterns
+= [
path('signup/', views.signup, name='signup'),
path('dashboard/', views.dashboard, name='dashboard'),
path('accounts/', include('django.contrib.auth.urls')), # login/logout
]
signup.html and dashboard.html templates already shown above.
✅ Run server → test:
- /signup/
→ create user
- /accounts/login/
→ login
- /dashboard/
→ accessible only after login
- /accounts/logout/
→ logout
What
you learned this week:
- Use Django’s built-in User model
- Create signup pages
- Create login/logout
- Protect views with @login_required
- Display current logged-in user info
Week 6: Django + MySQL
Prerequisite: Django basics, models, and authentication from previous
weeks.
Day
1 (Monday): Install MySQL and Connector
What we’re doing:
- Install MySQL and the Python connector so Django can
communicate with MySQL.
Steps:
- Install MySQL server (if not installed).
- Install Python MySQL client:
pip
install mysqlclient
Note: On Windows, you may need to
install pip install PyMySQL instead.
- Create a MySQL database for Django:
CREATE
DATABASE mysite_db;
- Test connection with Python:
import
MySQLdb
db
= MySQLdb.connect(host="localhost", user="root", passwd="yourpassword",
db="mysite_db")
print("Connected!")
Assignment:
👉 Install MySQL, create database mysite_db, and test connection using Python.
Day
2 (Tuesday): Configure Django to Use MySQL
What we’re doing:
- Update settings.py to connect Django project to MySQL.
Steps:
mysite/settings.py
DATABASES
= {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'mysite_db',
'USER': 'root',
'PASSWORD': 'yourpassword',
'HOST':
'localhost',
'PORT': '3306',
}
}
- Test connection by running migrations:
python
manage.py migrate
- Tables will now be created in MySQL instead of SQLite.
Assignment:
👉 Configure Django to use your MySQL database and run migrate to create tables.
Day
3 (Wednesday): Models with MySQL
What we’re doing:
- Use Django models as usual; now data will be stored in
MySQL.
Example:
blog/models.py
from
django.db import models
class
Student(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
city = models.CharField(max_length=100)
def __str__(self):
return self.name
Steps:
python
manage.py makemigrations
python
manage.py migrate
Test in Django shell:
from
blog.models import Student
Student.objects.create(name="John",
age=20, city="Abuja")
Student.objects.all()
- Data will now be saved in MySQL database.
Assignment:
👉 Create Book
model with fields title,
author, year. Add 3 books using Django shell.
Day
4 (Thursday): CRUD Operations with MySQL
What we’re doing:
- Perform Create, Read, Update, Delete operations
in Django using MySQL as database.
Example:
from
blog.models import Book
#
Create
Book.objects.create(title="Python
Basics", author="Raheem", year=2025)
#
Read
books
= Book.objects.all()
for
b in books:
print(b.title, b.author, b.year)
#
Update
b
= Book.objects.get(id=1)
b.year
= 2024
b.save()
#
Delete
b.delete()
Assignment:
👉 Using the Student model:
- Add 2 students
- List all students
- Update age of one student
- Delete one student
Day
5 (Friday): Assessment
What we’re doing:
- Test your knowledge of Django + MySQL: database
connection, models, and CRUD operations.
Task:
- Connect Django project to MySQL (mysite_db)
- Create Book model (title, author, year)
- Add at least 3 books using Django shell
- List all books
- Update the year of one book
- Delete one book
Solution:
settings.py (database configuration)
DATABASES
= {
'default': {
'ENGINE':
'django.db.backends.mysql',
'NAME': 'mysite_db',
'USER': 'root',
'PASSWORD': 'yourpassword',
'HOST': 'localhost',
'PORT': '3306',
}
}
blog/models.py
from
django.db import models
class
Book(models.Model):
title = models.CharField(max_length=200)
author = models.CharField(max_length=100)
year = models.IntegerField()
def __str__(self):
return self.title
Django shell operations:
from
blog.models import Book
#
Create
Book.objects.create(title="Python
Basics", author="Raheem", year=2025)
Book.objects.create(title="Django
Essentials", author="Ada", year=2024)
Book.objects.create(title="MySQL
Guide", author="John", year=2023)
#
Read
books
= Book.objects.all()
for
b in books:
print(b.title, b.author, b.year)
#
Update
b
= Book.objects.get(id=1)
b.year
= 2024
b.save()
#
Delete
b
= Book.objects.get(id=3)
b.delete()
Check MySQL database → should
reflect all changes
What
you learned this week:
- Install MySQL and connector
- Configure Django to use MySQL
- Use Django models with MySQL
- Perform CRUD operations with MySQL database
Week 7: Django Forms + ModelForms + CRUD in Templates
Prerequisite: Django + MySQL from Week 6.
Day
1 (Monday): Introduction to Django Forms
What we’re doing:
- Learn how to create forms in Django to collect user
input.
- Two types: Form (manual fields) and ModelForm
(linked to models).
Example (Form):
blog/forms.py
from
django import forms
class
ContactForm(forms.Form):
name = forms.CharField(max_length=100)
email = forms.EmailField()
message =
forms.CharField(widget=forms.Textarea)
blog/views.py
from
django.shortcuts import render
from
.forms import ContactForm
def
contact(request):
form = ContactForm()
return render(request, 'contact.html', {'form':
form})
blog/templates/contact.html
<h2>Contact
Us</h2>
<form
method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Send</button>
</form>
Assignment:
👉 Create a contact form with fields: Name, Email, Message. Display it
in a template.
Day
2 (Tuesday): Introduction to ModelForms
What we’re doing:
- Create forms automatically linked to models. Saves time
for CRUD operations.
Example (ModelForm for Book):
blog/forms.py
from
django.forms import ModelForm
from
.models import Book
class
BookForm(ModelForm):
class Meta:
model = Book
fields = ['title', 'author', 'year']
blog/views.py
from
django.shortcuts import render, redirect
from
.forms import BookForm
def
add_book(request):
if request.method == 'POST':
form = BookForm(request.POST)
if form.is_valid():
form.save()
return redirect('book_list')
else:
form = BookForm()
return render(request, 'add_book.html', {'form':
form})
blog/templates/add_book.html
<h2>Add
Book</h2>
<form
method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Save</button>
</form>
Assignment:
👉 Create BookForm and view add_book to add new books via template.
Day
3 (Wednesday): Display Records (Read)
What we’re doing:
- Display all records from the database in a template.
Example:
blog/views.py
from
.models import Book
def
book_list(request):
books = Book.objects.all()
return render(request, 'book_list.html', {'books':
books})
blog/templates/book_list.html
<h2>Books
List</h2>
<ul>
{%
for book in books %}
<li>{{ book.title }} by {{
book.author }} ({{ book.year }})</li>
{%
endfor %}
</ul>
<a
href="{% url 'add_book' %}">Add New Book</a>
Assignment:
👉 Create a page to list all books with a link to add a new book.
Day
4 (Thursday): Update & Delete Records
What we’re doing:
- Learn to edit and delete records using views and
templates.
Example:
blog/views.py
from
django.shortcuts import get_object_or_404
def
edit_book(request, id):
book = get_object_or_404(Book, id=id)
if request.method == 'POST':
form = BookForm(request.POST,
instance=book)
if form.is_valid():
form.save()
return redirect('book_list')
else:
form = BookForm(instance=book)
return render(request, 'edit_book.html', {'form':
form})
def
delete_book(request, id):
book = get_object_or_404(Book, id=id)
if request.method == 'POST':
book.delete()
return redirect('book_list')
return render(request, 'delete_book.html',
{'book': book})
edit_book.html
<h2>Edit
Book</h2>
<form
method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Update</button>
</form>
delete_book.html
<h2>Delete
Book</h2>
<p>Are
you sure you want to delete "{{ book.title }}"?</p>
<form
method="post">
{% csrf_token %}
<button type="submit">Yes,
Delete</button>
</form>
<a
href="{% url 'book_list' %}">Cancel</a>
urls.py
from
blog import views
urlpatterns
+= [
path('books/', views.book_list, name='book_list'),
path('books/add/', views.add_book, name='add_book'),
path('books/edit/<int:id>/',
views.edit_book, name='edit_book'),
path('books/delete/<int:id>/',
views.delete_book, name='delete_book'),
]
Assignment:
👉 Implement edit and delete pages for books. Test by adding, editing,
and deleting records.
Day
5 (Friday): Assessment
What we’re doing:
- Friday assessment to test full CRUD with forms,
ModelForms, and templates.
Task:
- Create BookForm (ModelForm)
- Create pages:
- List books (book_list.html)
- Add book (add_book.html)
- Edit book (edit_book.html)
- Delete book (delete_book.html)
- Ensure CRUD works: add → edit → delete
Solution:
- forms.py,
views.py,
urls.py, and
templates already shown above.
- Test full flow in browser:
- /books/
→ list books
- /books/add/
→ add a book
- /books/edit/1/
→ edit book with id=1
- /books/delete/1/
→ delete book with id=1
All operations should reflect in
MySQL database.
What
you learned this week:
- Use Django Forms and ModelForms
- Create add/edit/delete pages for models
- Display database records in templates
- Full CRUD functionality in Django
Week 8: Django Advanced – User Profiles, Permissions,
Search, and Filtering
Prerequisite: Django Forms + ModelForms + CRUD (Week 7).
Day
1 (Monday): User Profiles
What we’re doing:
- Extend Django’s built-in User model to store extra
information like profile picture, bio, or phone number.
Example:
blog/models.py
from
django.contrib.auth.models import User
from
django.db import models
class
UserProfile(models.Model):
user = models.OneToOneField(User,
on_delete=models.CASCADE)
phone = models.CharField(max_length=20,
blank=True)
bio = models.TextField(blank=True)
profile_pic = models.ImageField(upload_to='profiles/',
blank=True, null=True)
def __str__(self):
return self.user.username
- Use signals to auto-create profile when a user
registers:
blog/signals.py
from
django.db.models.signals import post_save
from
django.dispatch import receiver
from
django.contrib.auth.models import User
from
.models import UserProfile
@receiver(post_save,
sender=User)
def
create_user_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
- Add signals.py in apps.py to load signals:
def
ready(self):
import blog.signals
Assignment:
👉 Extend your signup flow to include UserProfile with phone
and bio. Display it on profile page.
Day
2 (Tuesday): Permissions
What we’re doing:
- Restrict access to certain pages using permissions and
groups.
Example:
views.py
from
django.contrib.auth.decorators import permission_required
@permission_required('blog.add_book',
login_url='/accounts/login/')
def
add_book(request):
# Only users with permission 'add_book' can
access
...
- Add users to groups and assign permissions in Django
admin (/admin/).
Assignment:
👉 Create a group Editors with permission to add/edit books. Only allow group members
to access /books/add/ and /books/edit/<id>/.
Day
3 (Wednesday): Search Functionality
What we’re doing:
- Allow users to search for records in the database using
forms.
Example:
views.py
def
search_books(request):
query = request.GET.get('q')
if query:
books = Book.objects.filter(title__icontains=query)
else:
books = Book.objects.all()
return render(request, 'search_books.html',
{'books': books})
search_books.html
<form
method="get">
<input type="text" name="q"
placeholder="Search books">
<button type="submit">Search</button>
</form>
<ul>
{%
for book in books %}
<li>{{ book.title }} by {{
book.author }} ({{ book.year }})</li>
{%
empty %}
<li>No books found</li>
{%
endfor %}
</ul>
Assignment:
👉 Add search functionality to your book list page.
Day
4 (Thursday): Filtering Records
What we’re doing:
- Filter records by attributes like year or author.
Example:
views.py
def
filter_books(request):
year = request.GET.get('year')
if year:
books = Book.objects.filter(year=year)
else:
books = Book.objects.all()
return render(request, 'filter_books.html',
{'books': books})
filter_books.html
<form
method="get">
<input
type="number" name="year" placeholder="Enter
year">
<button type="submit">Filter</button>
</form>
<ul>
{%
for book in books %}
<li>{{ book.title }} by {{
book.author }} ({{ book.year }})</li>
{%
empty %}
<li>No books found</li>
{%
endfor %}
</ul>
Assignment:
👉 Add a filter page to filter books by year.
Day
5 (Friday): Assessment
What we’re doing:
- Friday test: Check if you understand user profiles,
permissions, search, and filtering.
Task:
- Extend User model with UserProfile (phone, bio).
- Create group Editors with add/edit book permissions.
- Protect /books/add/ and /books/edit/<id>/ so only Editors can access.
- Add search functionality on book list page.
- Add filter by year functionality.
Solution:
- UserProfile
model, signals, and profile page as shown above.
- Permissions using @permission_required decorator.
- Search with icontains query.
- Filter with Book.objects.filter(year=year) and input form.
- Test all functionalities in browser.
At the end of Week 8, your project
should support:
- User profiles with extra info
- Permission-based access to pages
- Searching books by title
- Filtering books by year
Week 9: Django Deployment + Static & Media Files
Prerequisite: Django Advanced (Week 8), User Profiles, CRUD, Forms,
MySQL.
Day
1 (Monday): Understanding Static & Media Files
What we’re doing:
- Learn the difference between static files and media
files.
- Static files:
CSS, JS, images used in templates.
- Media files:
User-uploaded content (profile pictures, documents).
Example:
settings.py
#
Static files
STATIC_URL
= '/static/'
STATICFILES_DIRS
= [BASE_DIR / "static"]
#
Media files
MEDIA_URL
= '/media/'
MEDIA_ROOT
= BASE_DIR / "media"
Assignment:
👉 Create folders static/ and media/
in project root. Add a CSS file in static/ and an image in media/.
Day
2 (Tuesday): Using Static Files
What we’re doing:
- Serve CSS and JS files in templates.
Example:
static/style.css
body
{
font-family: Arial;
background-color: #f0f0f0;
}
templates/home.html
{%
load static %}
<link
rel="stylesheet" href="{% static 'style.css' %}">
<h1>Welcome
to My Blog</h1>
- Run server → CSS applied
Assignment:
👉 Add a CSS file to style your book list page and profile page.
Day
3 (Wednesday): Handling Media Files
What we’re doing:
- Allow users to upload files like profile pictures.
Example:
models.py (already shown in Week 8)
profile_pic
= models.ImageField(upload_to='profiles/', blank=True, null=True)
forms.py
class
UserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ['phone', 'bio', 'profile_pic']
views.py
from
django.conf import settings
from
django.conf.urls.static import static
def
edit_profile(request):
profile = request.user.userprofile
if request.method == 'POST':
form = UserProfileForm(request.POST,
request.FILES, instance=profile)
if form.is_valid():
form.save()
return redirect('profile')
else:
form =
UserProfileForm(instance=profile)
return render(request, 'edit_profile.html',
{'form': form})
urlpatterns
+= static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
edit_profile.html
<form
method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Update
Profile</button>
</form>
Assignment:
👉 Allow users to upload a profile picture. Display it on the profile
page.
Day
4 (Thursday): Deployment Basics
What we’re doing:
- Prepare Django project for deployment online.
- Deploy using PythonAnywhere or Heroku
(common free options).
Steps (PythonAnywhere Example):
- Sign up on pythonanywhere.com.
- Upload project folder using Files tab or Git.
- Create virtual environment on PythonAnywhere.
- Install requirements:
pip
install -r requirements.txt
- Configure WSGI file to point to mysite/wsgi.py.
- Set database and static file settings.
- Reload web app → your Django site is live.
Assignment:
👉 Prepare your project for deployment by:
- Freezing requirements: pip
freeze > requirements.txt
- Ensuring STATIC_ROOT is set in settings.py:
STATIC_ROOT
= BASE_DIR / "staticfiles"
Day
5 (Friday): Assessment
What we’re doing:
- Friday assessment to test static files, media files,
and deployment preparation.
Task:
- Add CSS to style home, book list, and profile pages.
- Enable user to upload a profile picture and display it.
- Configure project for deployment (requirements.txt,
STATIC_ROOT, MEDIA_ROOT).
Solution:
- Static files:
{% load static %}
in templates, CSS/JS in static/ folder.
- Media files:
Model ImageField, forms with enctype="multipart/form-data", settings MEDIA_URL and MEDIA_ROOT.
- Deployment:
- STATIC_ROOT
set
- python manage.py collectstatic to gather static files
- requirements.txt
with all dependencies
- Test project locally before uploading
✅ Project is now deployment-ready
with static & media files configured.
What
you learned this week:
- Difference between static and media files
- How to serve CSS/JS and upload user files
- Prepare Django project for online deployment
Week 10: Django Final Project – Combining Everything
Goal: Build a Book Management System where users can
register, login, manage books, upload profiles, search, filter, and deploy the
project online.
Day
1 (Monday): Project Setup
What we’re doing:
- Create a fresh Django project and app.
- Set up MySQL as the database.
Steps:
- Create project and app:
django-admin
startproject booksite
cd
booksite
python
manage.py startapp library
- Add app to INSTALLED_APPS in settings.py:
INSTALLED_APPS
= [
...
'library',
]
- Configure MySQL in settings.py (as Week 6):
DATABASES
= {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'booksite_db',
'USER': 'root',
'PASSWORD': 'yourpassword',
'HOST': 'localhost',
'PORT': '3306',
}
}
- Run migrations:
python
manage.py migrate
Assignment:
👉 Set up a new Django project and MySQL database ready for the final
project.
Day
2 (Tuesday): Models & User Profiles
What we’re doing:
- Create models for Book and UserProfile.
Example:
library/models.py
from
django.db import models
from
django.contrib.auth.models import User
class
Book(models.Model):
title = models.CharField(max_length=200)
author = models.CharField(max_length=100)
year = models.IntegerField()
def __str__(self):
return self.title
class
UserProfile(models.Model):
user = models.OneToOneField(User,
on_delete=models.CASCADE)
phone = models.CharField(max_length=20,
blank=True)
bio = models.TextField(blank=True)
profile_pic = models.ImageField(upload_to='profiles/',
blank=True, null=True)
def __str__(self):
return self.user.username
- Use signals to auto-create profile on user
signup (Week 8).
Assignment:
👉 Create Book
and UserProfile models
and apply migrations.
Day
3 (Wednesday): Forms, ModelForms, and Views
What we’re doing:
- Create signup, login, edit profile and book
CRUD forms using ModelForms.
Example:
library/forms.py
from
django import forms
from
django.contrib.auth.forms import UserCreationForm
from
django.contrib.auth.models import User
from
.models import UserProfile, Book
class
SignUpForm(UserCreationForm):
email = forms.EmailField(required=True)
class Meta:
model = User
fields = ('username', 'email', 'password1',
'password2')
class
UserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ['phone', 'bio', 'profile_pic']
class
BookForm(forms.ModelForm):
class Meta:
model = Book
fields = ['title', 'author', 'year']
Views:
- Signup, login, logout, dashboard, profile,
add/edit/delete book (Week 7 & 8 examples).
Assignment:
👉 Implement signup, login/logout, dashboard, profile, add/edit/delete
books.
Day
4 (Thursday): Search, Filter, and Static/Media Files
What we’re doing:
- Implement search by book title and filter by
year.
- Use CSS for styling and allow profile picture
uploads.
Example Views:
views.py
def
search_books(request):
query = request.GET.get('q')
books = Book.objects.filter(title__icontains=query)
if query else Book.objects.all()
return render(request, 'search_books.html',
{'books': books})
def
filter_books(request):
year = request.GET.get('year')
books = Book.objects.filter(year=year) if
year else Book.objects.all()
return render(request, 'filter_books.html',
{'books': books})
Static & Media Settings
(settings.py):
STATIC_URL
= '/static/'
STATICFILES_DIRS
= [BASE_DIR / "static"]
MEDIA_URL
= '/media/'
MEDIA_ROOT
= BASE_DIR / "media"
Assignment:
👉 Add search and filter pages, include CSS styling, and allow profile
picture uploads.
Day
5 (Friday): Final Assessment
What we’re doing:
- Test the complete project.
Task:
- Signup, login/logout users.
- Edit profile with phone, bio, and profile picture.
- Add, edit, delete books.
- Search books by title and filter by year.
- Display books and user profiles with CSS styling.
- Prepare project for deployment (collect static files,
requirements.txt, media files).
Solution Overview:
- Models: Book, UserProfile
- Forms: SignUpForm, UserProfileForm, BookForm
- Views: Signup, login, logout, dashboard, profile,
add/edit/delete books, search, filter
- Templates: For all pages with {% load static %},
CSS, and media files
- URLs: Map all views to URLs
- Deployment prep: STATIC_ROOT, MEDIA_ROOT, python manage.py
collectstatic, requirements.txt
Django 10-Week Cheat Sheet
1.
Project & App Setup
#
Create project
django-admin
startproject projectname
cd
projectname
#
Create app
python
manage.py startapp appname
#
Run server
python
manage.py runserver
#
Migrate database
python
manage.py migrate
python
manage.py makemigrations appname
python
manage.py migrate appname
2.
MySQL Configuration (Week 6)
#
settings.py
DATABASES
= {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'dbname',
'USER': 'root',
'PASSWORD': 'yourpassword',
'HOST': 'localhost',
'PORT': '3306',
}
}
3.
Models
from
django.db import models
from
django.contrib.auth.models import User
class
Book(models.Model):
title = models.CharField(max_length=200)
author = models.CharField(max_length=100)
year = models.IntegerField()
class
UserProfile(models.Model):
user
= models.OneToOneField(User, on_delete=models.CASCADE)
phone = models.CharField(max_length=20,
blank=True)
bio = models.TextField(blank=True)
profile_pic = models.ImageField(upload_to='profiles/',
blank=True, null=True)
4.
Forms & ModelForms
from
django import forms
from
django.contrib.auth.forms import UserCreationForm
from
django.contrib.auth.models import User
from
.models import Book, UserProfile
class
SignUpForm(UserCreationForm):
email = forms.EmailField(required=True)
class Meta:
model = User
fields = ('username','email','password1','password2')
class
BookForm(forms.ModelForm):
class Meta:
model = Book
fields = ['title','author','year']
class
UserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ['phone','bio','profile_pic']
5.
Views
from
django.shortcuts import render, redirect, get_object_or_404
from
django.contrib.auth.decorators import login_required, permission_required
from
.models import Book, UserProfile
from
.forms import BookForm, SignUpForm, UserProfileForm
#
Signup
def
signup(request):
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
form.save()
return redirect('login')
else:
form = SignUpForm()
return render(request,'signup.html',{'form':form})
#
Dashboard
@login_required
def
dashboard(request):
return render(request,'dashboard.html')
#
Add Book
@login_required
def
add_book(request):
form
= BookForm(request.POST or None)
if form.is_valid():
form.save()
return redirect('book_list')
return render(request,'add_book.html',{'form':form})
#
Edit Book
@login_required
def
edit_book(request,id):
book = get_object_or_404(Book,id=id)
form = BookForm(request.POST or None,
instance=book)
if form.is_valid():
form.save()
return redirect('book_list')
return render(request,'edit_book.html',{'form':form})
#
Delete Book
@login_required
def
delete_book(request,id):
book = get_object_or_404(Book,id=id)
if request.method=='POST':
book.delete()
return redirect('book_list')
return render(request,'delete_book.html',{'book':book})
#
Search Books
def
search_books(request):
query
= request.GET.get('q')
books = Book.objects.filter(title__icontains=query)
if query else Book.objects.all()
return render(request,'search_books.html',{'books':books})
#
Filter Books
def
filter_books(request):
year = request.GET.get('year')
books = Book.objects.filter(year=year) if
year else Book.objects.all()
return render(request,'filter_books.html',{'books':books})
#
Edit Profile
@login_required
def
edit_profile(request):
profile = request.user.userprofile
form = UserProfileForm(request.POST or None,
request.FILES or None, instance=profile)
if form.is_valid():
form.save()
return redirect('profile')
return render(request,'edit_profile.html',{'form':form})
6.
URLs
from
django.urls import path, include
from
. import views
urlpatterns
= [
path('signup/',views.signup,name='signup'),
path('dashboard/',views.dashboard,name='dashboard'),
path('books/',views.search_books,name='book_list'),
path('books/add/',views.add_book,name='add_book'),
path('books/edit/<int:id>/',views.edit_book,name='edit_book'),
path('books/delete/<int:id>/',views.delete_book,name='delete_book'),
path('books/filter/',views.filter_books,name='filter_books'),
path('profile/edit/',views.edit_profile,name='edit_profile'),
path('accounts/',include('django.contrib.auth.urls')),
# login/logout
]
7.
Templates
{%
load static %}
<link
rel="stylesheet" href="{% static 'style.css' %}">
<h1>Page
Title</h1>
<form
method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
- Use enctype="multipart/form-data" for file uploads.
- Static files: {%
load static %} and STATICFILES_DIRS
in settings.py
- Media files: MEDIA_URL and MEDIA_ROOT in settings.py
8.
Signals (Auto-create UserProfile)
from
django.db.models.signals import post_save
from
django.dispatch import receiver
from
django.contrib.auth.models import User
from
.models import UserProfile
@receiver(post_save,
sender=User)
def
create_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
9.
Static & Media Settings
STATIC_URL
= '/static/'
STATICFILES_DIRS
= [BASE_DIR / "static"]
MEDIA_URL
= '/media/'
MEDIA_ROOT
= BASE_DIR / "media"
- Collect static before deployment:
python
manage.py collectstatic
10.
Common Commands
#
Run server
python
manage.py runserver
#
Make migrations
python
manage.py makemigrations
python
manage.py migrate
#
Create superuser
python
manage.py createsuperuser
#
Open shell
python
manage.py shell
#
Install packages
pip
install django mysqlclient Pillow
0 comments:
Post a Comment