Django Note

DAY 1

What is Django and Its Advantages

1. What is Django?
Django is a high-level web framework written in Python. It helps developers create websites and web applications quickly, securely, and efficiently. Django follows the Model-View-Template (MVT) architecture, which makes it easy to organize your code.

2. Purpose of Django

  • To make web development faster and easier
  • To provide tools for handling databases, URLs, templates, and web content
  • To ensure security and maintainable code for web applications

3. Advantages of Using Django

  • Rapid Development: Build web applications quickly with built-in features like authentication and admin panel
  • Security: Protects against common security threats like SQL injection and cross-site scripting
  • Scalability and Maintainability: Its modular structure allows your website to grow easily
  • Free and Open-Source: No cost and has a large community support

4. Real-World Uses of Django
Django is used to build:

  • Social networking websites
  • E-commerce platforms
  • Content management systems (CMS)
  • Dashboards and analytics platforms

5. Why Django is Popular

  • Easy to use for Python developers
  • Comes with many built-in features
  • Focuses on security and efficiency
  • Supported by a large community with tutorials and documentation

6. Key Points to Remember

  • Django helps you create professional web applications quickly
  • It is secure, scalable, and maintainable
  • Many popular websites like Instagram and Pinterest use Django

Assignment for Students:

  • Write a short paragraph explaining why Django is popular for web development.
  • Give one real-world example of a website or application built with Django.

DAY 2

Installing Python, Django & Setting Up Virtual Environment

1. Installing Python
Python is the programming language used to develop Django applications. Before starting Django, you must install Python on your computer.

  • Steps to install Python:

1.     Download the latest version of Python from the official website: https://www.python.org/downloads/

2.     Run the installer and select “Add Python to PATH” before clicking Install.

3.     Verify installation by opening a terminal/command prompt and typing:

4.  python --version

You should see the installed Python version.


2. Understanding Virtual Environments
virtual environment is an isolated workspace that allows you to install Python packages for a specific project without affecting other projects on your computer.

  • Benefits of using a virtual environment:
    • Keeps project dependencies separate
    • Avoids version conflicts between projects
    • Makes it easier to manage and deploy Django applications

3. Creating a Virtual Environment

  • Steps to create a virtual environment:

1.     Open your terminal or command prompt

2.     Navigate to your project folder

3.     Run the command:

4.  python -m venv myenv

(Here, myenv is the name of the virtual environment. You can choose any name.)

5.     Activate the virtual environment:

§  Windows:

§  myenv\Scripts\activate

§  Mac/Linux:

§  source myenv/bin/activate

  • Once activated, your terminal will show the virtual environment name at the beginning of the line, e.g., (myenv)

4. Installing Django in the Virtual Environment

  • With the virtual environment activated, install Django using pip:

·         pip install django

  • Verify the installation by typing:

·         python -m django --version

  • If successful, the terminal will display the installed Django version.

5. Summary / Key Points

  • Python must be installed before Django.
  • A virtual environment isolates your project’s packages.
  • Always activate the virtual environment before installing Django.
  • Verify installation using python -m django --version.

Classwork:

  • Install Python on your computer
  • Create a virtual environment for your project
  • Install Django in the virtual environment

Assignment:

  • Take a screenshot of your virtual environment activated with Django installed
  • Run python -m django --version and include the output in your submission

 

 

DAY 3;

HOW TO BUILD YOUR FIRST WEBPAGE USING DJANGO

 

We have 2 steps 1; creating of django project and 2- creating django app

 

HOW TO CREATE A DJANGO PROJECT


✅ STEP 1 — Install Python

Make sure Python is installed.

Open Command Prompt and type:

python --version
python -m django --version

If it shows a version (e.g., Python 3.10), continue.
If not, download from python.org.


✅ STEP 2 — Create a Project Folder

Choose where you want your project.

Example:

mkdir django_first cd django_first

✅ STEP 3 — Create a Virtual Environment

This helps keep your project clean.

python -m venv myenv

Activate it:

Windows

myenv\Scripts\activate

❗ If you get “running scripts is disabled” error

Run this once:

Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy RemoteSigned

Then activate again.


✅ STEP 4 — Install Django

pip install django
pip install django==4.2

✅ STEP 5 — Create Your First Django Project

django-admin startproject myproject.

Move inside the project:

cd myproject

Your folder will look like:

myproject/ manage.py myproject/ settings.py urls.py asgi.py wsgi.py

✅ STEP 6 — Start the Development Server

python manage.py runserver

You will see something like:

Starting development server at http://127.0.0.1:8000/

Open your browser and go to:

👉 http://127.0.0.1:8000

You will see:

🎉 “The install worked successfully! Congratulations!”

This is your first Django welcome page.


OPTIONAL — Make Your Own Welcome Page

Step 7: Create an App in the django folder

python manage.py startapp home

Step 8: Add the App to Settings register the app in django project

Open:

myproject/settings.py

Find INSTALLED_APPS and add:

'home',

Step 9: Create a View in Your App (what you want your app to show )

Open:

home/views.py

Add this:

from django.http import HttpResponse def welcome(request): return HttpResponse("Welcome to my first Django project!")

Step 10: Add URL your app url link

Open:

myproject/urls.py

Add:

from django.contrib import admin from django.urls import path from home.views import welcome urlpatterns = [ path('admin/', admin.site.urls), path('', welcome), # homepage ]

😊 Final Result

Now run:

python manage.py runserver

Visit:

👉 http://127.0.0.1:8000

You will see:

Welcome to my first Django project!

 


HOW TO NAVIGATE BACK TO MAIN FOLDER

On Windows (Command Prompt / PowerShell)

  • To go up one folder:

cd ..

  • To go up multiple levels, repeat .. with \:

cd ..\..

  • To go directly to your home folder:

cd %HOMEPATH%


2️ On Mac / Linux (Terminal)

  • To go up one folder:

cd ..

  • To go up multiple levels:

cd ../..

  • To go directly to your home folder:

cd ~


3️ Extra Useful Commands

Command

What it does

pwd

Shows your current folder path

ls / dir

Lists files and folders in current folder

cd foldername

Enter a folder inside current folder


✅ Tip:
If you’re inside your Django project and want to go back to the outer folder (where your virtual environment lives), just do:

cd ..

 


WORKING WITH TEMPLATE

Single-Page Django Website (Home Page)


STEP 1 — Create Django Project

Open your terminal:

django-admin startproject singlepage

cd singlepage

Structure:

singlepage/

├── manage.py

└── singlepage/

    ├── __init__.py

    ├── settings.py

    ├── urls.py

    ├── wsgi.py

    └── asgi.py


STEP 2 — Create an App

python manage.py startapp pages

Structure now:

singlepage/

└── pages/

    ├── __init__.py

    ├── admin.py

    ├── apps.py

    ├── models.py

    ├── tests.py

    └── views.py


STEP 3 — Add App to Settings

Open singlepage/settings.py → INSTALLED_APPS:

INSTALLED_APPS = [

    'django.contrib.admin',

    'django.contrib.auth',

    'django.contrib.contenttypes',

    'django.contrib.sessions',

    'django.contrib.messages',

    'django.contrib.staticfiles',

    'pages',   # Add your app here

]


STEP 4 — Create a View

Open pages/views.py and add:

from django.shortcuts import render

 

def home(request):

    return render(request, 'home.html')


STEP 5 — Create Template Folder

Inside your app pages/, create:

pages/templates/

Create home.html:

<!DOCTYPE html>

<html>

<head>

    <title>Home Page</title>

</head>

<body>

    <h1>Welcome to My Single-Page Django Website</h1>

    <p>This is a simple page created with Django.</p>

</body>

</html>

Folder structure now:

singlepage/

└── pages/

    └── templates/

        └── home.html


STEP 6 — Add URL

Open singlepage/urls.py and update:

from django.contrib import admin

from django.urls import path

from pages.views import home

 

urlpatterns = [

    path('admin/', admin.site.urls),

    path('', home),   # Home page

]


STEP 7 — Run the Server

python manage.py runserver

Open your browser:

http://127.0.0.1:8000/

You should see:

“Welcome to My Single-Page Django Website”


✅ Final Folder Structure for Single Page

singlepage/

├── manage.py

├── singlepage/

│   ├── __init__.py

│   ├── settings.py

│   ├── urls.py

│   ├── wsgi.py

│   └── asgi.py

└── pages/

    ├── __init__.py

    ├── admin.py

    ├── apps.py

    ├── models.py

    ├── tests.py

    ├── views.py

    └── templates/

        └── home.html

 

CREATE A SMALL WEBSITE WITH 3 PAGES USING DJANGO.

STEP 1 — Create Django Project

In your terminal:

django-admin startproject smallsite cd smallsite

✅ STEP 2 — Create an App For the Pages

python manage.py startapp pages

✅ STEP 3 — Add App to Settings

Open:

smallsite/settings.py

Find INSTALLED_APPS and add:

'pages',

✅ STEP 4 — Create 3 Views (Home, About, Contact)

Open:

pages/views.py

Replace everything with:

from django.shortcuts import render def home(request): return render(request, 'home.html') def about(request): return render(request, 'about.html') def contact(request): return render(request, 'contact.html')

✅ STEP 5 — Create Templates Folder

Inside your project, create:

pages/templates/

Inside this folder, create:

📄 home.html

<!DOCTYPE html> <html> <head> <title>Home</title> </head> <body> <h1>Welcome to our Home Page</h1> <a href="/">Home</a> | <a href="/about/">About</a> | <a href="/contact/">Contact</a> </body> </html>

📄 about.html

<!DOCTYPE html> <html> <head> <title>About</title> </head> <body> <h1>About Us</h1> <p>This is a small Django website with 3 pages.</p> <a href="/">Home</a> | <a href="/about/">About</a> | <a href="/contact/">Contact</a> </body> </html>

📄 contact.html

<!DOCTYPE html> <html> <head> <title>Contact</title> </head> <body> <h1>Contact Us</h1> <p>You can reach us at: example@gmail.com</p> <a href="/">Home</a> | <a href="/about/">About</a> | <a href="/contact/">Contact</a> </body> </html>

✅ STEP 6 — Add URLs

Open:

smallsite/urls.py

Replace it with:

from django.contrib import admin from django.urls import path from pages.views import home, about, contact urlpatterns = [ path('admin/', admin.site.urls), path('', home), # home page path('about/', about), # about page path('contact/', contact), # contact page ]

✅ STEP 7 — Run Server

python manage.py runserver

Now open your browser:

🎉 You now have a small Django website with 3 pages!

 

WEEK 2;

working with static folder 

Python 3.12.3 + Django 4.2.x

Installation Recommendation

1.      Activate your virtual environment (always use venv for projects):

python -m venv myenv
myenv\Scripts\activate

2.      Install Django 4.2.x explicitly:

pip install django==4.2

3.      Verify versions:

python --version
# Should show: Python 3.12.3
 
python -m django --version
# Should show: 4.2.x
 

STEP-BY-STEP: 1-Page Styled Django Project


STEP 1 — Install Python 3.12.3

  1. Go to the official Python website:
    https://www.python.org/downloads/release/python-3123/
  2. Download Windows Installer (64-bit).
  3. During installation:
    • ✅ Check Add Python to PATH
    • ✅ Check Install launcher for all users
    • Proceed with default settings
  4. Verify installation in PowerShell or CMD:

python --version

Expected output:

Python 3.12.3


STEP 2 — Create Project Folder

Create a folder for your project:

mkdir C:\Users\Zbook\Desktop\styledsite

cd C:\Users\Zbook\Desktop\styledsite


STEP 3 — Create Virtual Environment (Recommended)

python -m venv myenv

Activate it:

myenv\Scripts\activate

You should see (myenv) in your terminal prompt.


STEP 4 — Install Django 4.2.x

Inside the virtual environment, run:

pip install django==4.2

Check Django version:

python -m django --version

Expected output:

4.2.x


STEP 5 — Start Django Project

django-admin startproject styledsite .

Folder structure:

styledsite/

├── manage.py

└── styledsite/

    ├── __init__.py

    ├── settings.py

    ├── urls.py

    ├── wsgi.py

    └── asgi.py


STEP 6 — Create Django App

python manage.py startapp pages

Folder structure:

pages/

├── __init__.py

├── admin.py

├── apps.py

├── models.py

├── tests.py

└── views.py


STEP 7 — Add App to Settings

Open styledsite/settings.py → INSTALLED_APPS:

INSTALLED_APPS = [

    'django.contrib.admin',

    'django.contrib.auth',

    'django.contrib.contenttypes',

    'django.contrib.sessions',

    'django.contrib.messages',

    'django.contrib.staticfiles',

    'pages',   # <-- add your app here

]


STEP 8 — Create View

Open pages/views.py and add:

from django.shortcuts import render

 def home(request):

    return render(request, 'pages/home.html')


STEP 9 — Create Template Folder and HTML

Inside pages/, create:

pages/templates/pages/

Create home.html:

<!DOCTYPE html>

<html>

<head>

    <title>Home Page</title>

    {% load static %}

    <link rel="stylesheet" href="{% static 'pages/style.css' %}">

</head>

<body>

    <header>

        <h1>Welcome to My Styled Django Page</h1>

    </header>

    <main>

        <p>This is a fully styled page using CSS!</p>

        <button>Click Me</button>

    </main>

    <footer>

        <p>© 2025 My Django Website</p>

    </footer>

</body>

</html>

Folder structure:

pages/

└── templates/

    └── pages/

        └── home.html


STEP 10 — Add CSS

Inside pages/, create:

pages/static/pages/

Create style.css:

body {

    font-family: Arial, sans-serif;

    background-color#f0f8ff;

    margin0;

    padding0;

}

 

header {

    background-color#4CAF50;

    color: white;

    text-align: center;

    padding30px;

}

 

main {

    text-align: center;

    margin-top50px;

}

 

button {

    padding10px 20px;

    background-color#4CAF50;

    border: none;

    color: white;

    font-size16px;

    cursor: pointer;

    border-radius5px;

}

 

button:hover {

    background-color#45a049;

}

 

footer {

    text-align: center;

    background-color#222;

    color: white;

    padding15px;

    position: fixed;

    bottom0;

    width100%;

}

Folder structure:

pages/

└── static/

    └── pages/

        └── style.css


STEP 11 — Add URL

Open styledsite/urls.py:

from django.contrib import admin

from django.urls import path

from pages.views import home

 

urlpatterns = [

    path('admin/', admin.site.urls),

    path('', home),

]


STEP 12 — Apply Migrations

python manage.py migrate


STEP 13 — Run Server

python manage.py runserver

Open browser:

http://127.0.0.1:8000/

You will see a fully styled page with header, main content, button, and footer.


✅ Full Folder Structure


styledsite/

├── manage.py

├── styledsite/

│   ├── __init__.py

│   ├── settings.py

│   ├── urls.py

│   ├── wsgi.py

│   └── asgi.py

└── pages/

    ├── __init__.py

    ├── admin.py

    ├── apps.py

    ├── models.py

    ├── tests.py

    ├── views.py

    ├── templates/

    │   └── pages/

    │       └── home.html

    └── static/

        └── pages/

            └── style.css

MODEL

A model means creating a Table to store a record or data like  Name, Age

STEPS USED TO CREATE A MODEL

STEP 1: Decide what you want to store

We want to store:

  • Student full name

  • Student course

STEP 2: Open models.py

In your app folder:

pages/models.py

STEP 3: Create a class

class Student(models.Model):

Meaning:

  • class Student → name of the table

  • models.Model → tells Django this is a database model

So Django understands:

“Student is a database table.”

✔ Every model must inherit from models.Model

STEP 3 CREATE A COLUMN NAME

fullname = models.CharField(max_length=100)
Meaning: fullname → column name CharField → text field max_length=100 → max 100 characters
STEP 4: METHOD TO SHOW NAME RECORD
def __str__(self):
        return self.fullname

Meaning:

  • This controls how the record is displayed

Instead of seeing:

Student object (1)

STEP 5: HOW DJANGO TURNS THIS INTO A TABLE

After writing the model:

STEP 1 — Make migration

python manage.py makemigrations

👉 Django creates instructions for the database.

STEP 2 — Apply migration

python manage.py migrate

👉 Django creates a table like this:

idfullnamecourse
1JohnMath
2MaryICT


FULL CODDE
class Student(models.Model):
    fullname = models.CharField(max_length=100)
    course = models.CharField(max_length=100)

    def __str__(self):
        return self.fullname
VIEW  Function in Django
How to create home function in view 
The home view displays the Home Page of your website.
def home(request):
    return render(request, 'pages/home.html')
 # 'render' is a Django function that displays an HTML page
 # 'request' contains all the information from the browser
 # 'pages/home.html' is the path to the HTML template we want to show
 # 'return' sends the rendered HTML back to the browser

CREATING OF MORE VIEWS 
from django.shortcuts import render # Home page view (already exists) def home(request): # Shows the home page return render(request, 'pages/home.html') # About page view def about(request): # Shows the About page return render(request, 'pages/about.html') # Contact page view def contact(request): # Shows the Contact Us page return render(request, 'pages/contact.html') 
CREATING A VIEW FOR REGISTER 
def register(request):
    # Check if the form was submitted
    if request.method == 'POST':
        # Get the value entered in the "fullname" input field of the form
        name = request.POST.get('fullname')
        # Get the value entered in the "course" input field of the form
        course = request.POST.get('course')

        # Create a new student record in the database using the data from the form
        Student.objects.create(
            fullname=name,  # Set the fullname column
            course=course   # Set the course column
        )

        # After saving, redirect the user to the students list page
        return redirect('/students/')

    # If the form was not submitted, just show the registration page
    return render(request, 'pages/register.html')

FUNCTION TO VIEW STUDENT RECORD 
def students(request):
    # Get all student records from the database
    students = Student.objects.all()

    # Render the 'students.html' template and send the list of students to it
    # The template can use 'students' variable to display all registered students
    return render(request, 'pages/students.html', {'students': students})


CREAYING A VIEW FOR REGISTER AND VIEW COMPLETE CODE 
def register(request):
    if request.method == 'POST':
        name = request.POST.get('fullname')
        course = request.POST.get('course')

        Student.objects.create(
            fullname=name,
            course=course
        )
        return redirect('/students/')

    return render(request, 'pages/register.html')


def students(request):
    students = Student.objects.all()
    return render(request, 'pages/students.html', {'students': students})

CREATING OF URL

# Import Django's admin module to use the built-in admin site
from django.contrib import admin

# Import 'path' function to map URLs to views
from django.urls import path

# Import the view functions from our pages app
from pages.views import home, register, students

# Define URL patterns: tells Django which view to run for each URL
urlpatterns = [
    # URL for Django admin site: /admin/
    path('admin/', admin.site.urls),

    # URL for home page: /
    path('', home),

    # URL for register page: /register/
    path('register/', register),

    # URL for students list page: /students/
    path('students/', students),
]

Create Register Page (HTML Form)

<!-- Heading for the registration page -->
<h2>Student Registration</h2>

<!-- Start of the registration form -->
<!-- method="POST" means the form will send data to the server -->
<form method="POST">
    
    <!-- CSRF token: security feature in Django to prevent cross-site attacks -->
    {% csrf_token %}

    <!-- Label and input for student's full name -->
    <label>Full Name:</label><br>
    <!-- 'name' attribute must match what the view expects (request.POST.get('fullname')) -->
    <input type="text" name="fullname" required><br><br>

    <!-- Label and input for student's course -->
    <label>Course:</label><br>
    <!-- 'name' attribute must match what the view expects (request.POST.get('course')) -->
    <input type="text" name="course" required><br><br>

    <!-- Submit button to send the form data -->
    <button type="submit">Register</button>
</form>

<br>

<!-- Link to go back to the home page -->
<a href="/">Back Home</a>

Topic: Django Template Language Basics

(Where {{ variable }}, {% for %}, and {% csrf_token %} come from)


Introduction

Django uses Python to handle data (in views and models) and HTML to display content.
Sometimes, we need to show Python data dynamically inside HTML.

This is where Django Template Language (DTL) comes in.
It allows HTML files to use Python-like syntax to display data, loop through lists, and secure forms.


Sub-Topic 1: {{ variable }}

  • What it is: A placeholder to show data from Python in HTML.

  • Where it comes from: Passed from the view using render(request, template, context).

  • How to write:

<p>{{ variable_name }}</p>
  • Example:

<p>{{ student.fullname }}</p>

Displays the fullname of a student from the database.


Sub-Topic 2: {% for ... in ... %}

  • What it is: A loop to repeat HTML for every item in a list or queryset.

  • Where it comes from: A Python list or Django model queryset passed from the view.

  • How to write:

{% for item in list %} {{ item }} {% endfor %}
  • Example:

<ul> {% for student in students %} <li>{{ student.fullname }} — {{ student.course }}</li> {% empty %} <li>No students registered yet</li> {% endfor %} </ul>
  • Optional: {% empty %} shows a message if the list is empty.


Sub-Topic 3: {% csrf_token %}

  • What it is: A security token used in POST forms to prevent malicious attacks (Cross-Site Request Forgery).

  • Where it comes from: Django automatically generates it for every session.

  • How to write:

<form method="POST"> {% csrf_token %} <!-- input fields here --> </form>
  • Example:

<form method="POST"> {% csrf_token %} <input type="text" name="fullname"> <button type="submit">Register</button> </form>

Always include {% csrf_token %} in every POST form.


Summary Table

DTL TagPurposeExample
{{ variable }}Show Python data in HTML{{ student.fullname }}
{% for item in list %}Loop through a list or queryset{% for student in students %} ... {% endfor %}
{% csrf_token %}Secure forms from attacksPlace inside <form method="POST">

Create VIEW Page (HTML Form)

<!-- Heading for the page -->
<h2>Registered Students</h2>

<!-- Start an unordered list to show all students -->
<ul>
    <!-- Loop through each student in the 'students' variable passed from the view -->
    {% for student in students %}
        <!-- Display each student's fullname and course in a list item -->
        <li>{{ student.fullname }} — {{ student.course }}</li>
    {% empty %}
        <!-- This shows if there are no students in the list -->
        <li>No student registered yet</li>
    {% endfor %}
</ul>

<br>

<!-- Link to go back to the home page -->
<a href="/">Back Home</a>
CREATING OF REGISTER FORM


➕ STEP 20 — Add Links on Home Page (SIMPLE METHOD)

Edit home.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <p>This is a fully styled page using CSS!</p>

    <a href="/register/">Register Student</a>
    <br><br>

    <a href="/students/">View Students</a>

</body>
</html>

✅ This uses the same method as:

<a href="/about/">About</a>

Create file:

📄 pages/templates/register.html


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <!DOCTYPE html>
<html>
<head>
    <title>Student Register</title>
</head>
<body>

<h2>Student Registration</h2>

<form method="POST">
    {% csrf_token %}

    <label>Full Name:</label><br>
    <input type="text" name="fullname" required><br><br>

    <label>Course:</label><br>
    <input type="text" name="course" required><br><br>

    <button type="submit">Register</button>
</form>

<br>
<a href="/">Back Home</a>

</body>
</html>
</body>
</html>
</html>

➕ STEP 14 — Create Student Model (Register Data)


Open pages/models.py

from django.db import models

# Create your models here.

class Student(models.Model):
    fullname = models.CharField(max_length=100)
    course = models.CharField(max_length=100)

    def __str__(self):
        return self.fullname

➕ STEP 15 — Make & Apply Migrations

Run in terminal:

python manage.py makemigrations
python manage.py migrate


➕ STEP 16 — Create Register & View Pages (Views)

Open pages/views.py
(keep your home view, ADD these)

from django.shortcuts import render, redirect
from .models import Student
def home(request):
    return render(request, 'home.html')
# Register student
def register(request):
    if request.method == 'POST':
        fullname = request.POST.get('fullname')
        course = request.POST.get('course')

        # Save the data to the Student model
        Student.objects.create(fullname=fullname, course=course)

        # Redirect to students list page
        return redirect('students')

    # If GET request, just show the form
    return render(request, 'register.html')


# Show all students
def students(request):
    students = Student.objects.all()
    return render(request, 'students.html', {'students': students})

👉 No forms.py used (very simple for beginners)


➕ STEP 17 — Add URLs (Simple Method)

Open styledsite/urls.py

from django.contrib import admin
from django.urls import path
from pages.views import  about, home,register, students



urlpatterns = [
    path('admin/', admin.site.urls),
    path('', home),          # home page
    path('about/', about),   # about page
    path('register/', register),   # about page
    path('students/', students, name='students'),  # ✅ MUST have name='students'


]


➕ STEP 19 — Create Students List Page (View Only)

Create file:

📄 pages/templates/students.html

<!DOCTYPE html>
<html>
<head>
    <title>Students List</title>
</head>
<body>

<h2>Registered Students</h2>

<ul>
    {% for student in students %}
        <li>{{ student.fullname }} — {{ student.course }}</li>
    {% empty %}
        <li>No student registered yet</li>
    {% endfor %}
</ul>

<br>
<a href="/">Back Home</a>

</body>
</html>


➕ STEP 21 — Restart Server

python manage.py runserver

How to create full crud
Home Page; HOME.HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <p>This is a fully styled page using CSS!</p>

    <a href="/register/">Register Student</a>
    <br><br>

    <a href="/students/">View Students</a>

</body>
</html>
<a href="/register/">Register Student</a>
<a href="{% url 'register' %}">Register Student</a>

It’s a clickable link that takes the user to the /register/ page when clicked.


REGISTER PAGE: REGISTER.HTML 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <!DOCTYPE html>
<html>
<head>
    <title>Student Register</title>
</head>
<body>

<h2>Student Registration</h2>

<form method="POST">
    {% csrf_token %}

    <label>Full Name:</label><br>
    <input type="text" name="fullname" required><br><br>

    <label>Course:</label><br>
    <input type="text" name="course" required><br><br>

    <button type="submit">Register</button>
</form>

<br>
<a href="/">Back Home</a>

</body>
</html>
</body>
</html>


STUDENTS.HTML

<!DOCTYPE html>
<html>
<head>
    <title>Students List</title>
</head>
<body>

<h2>Registered Students</h2>

<table border="1" cellpadding="10" cellspacing="0">
    <tr>
        <th>Full Name</th>
        <th>Course</th>
        <th>Action</th>
    </tr>

    {% for student in students %}
    <tr>
        <td>{{ student.fullname }}</td>
        <td>{{ student.course }}</td>
        <td>
            <a href="{% url 'edit_student' student.id %}">Edit</a>
            |
            <a href="{% url 'delete_student' student.id %}"
               onclick="return confirm('Are you sure you want to delete this student?')">
               Delete
            </a>
        </td>
    </tr>
    {% empty %}
    <tr>
        <td colspan="3">No student registered yet</td>
    </tr>
    {% endfor %}
</table>

<br>
<a href="{% url 'home' %}">Back Home</a>

</body>
</html>


MODEL.PY

from django.db import models

# Create your models here.

class Student(models.Model):
    fullname = models.CharField(max_length=100)
    course = models.CharField(max_length=100)

    def __str__(self):
        return self.fullname


VIEW.PY 

from django.shortcuts import render, redirect, get_object_or_404
from .models import Student

# HOME
def home(request):
    return render(request, 'home.html')

# CREATE (Register)
def register(request):
    if request.method == 'POST':
        fullname = request.POST.get('fullname')
        course = request.POST.get('course')

        Student.objects.create(
            fullname=fullname,
            course=course
        )

        return redirect('students')

    return render(request, 'register.html')

# READ (View all)
def students(request):
    students = Student.objects.all()
    return render(request, 'students.html', {'students': students})

# UPDATE
def edit_student(request, id):
    student = get_object_or_404(Student, id=id)

    if request.method == 'POST':
        student.fullname = request.POST.get('fullname')
        student.course = request.POST.get('course')
        student.save()

        return redirect('students')

    return render(request, 'edit_student.html', {'student': student})

# DELETE
def delete_student(request, id):
    student = get_object_or_404(Student, id=id)
    student.delete()
    return redirect('students')

URL.PY 

from django.contrib import admin
from django.urls import path
from pages.views import home, register, students, edit_student, delete_student

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', home, name='home'),
    path('register/', register, name='register'),
    path('students/', students, name='students'),
    path('edit/<int:id>/', edit_student, name='edit_student'),
    path('delete/<int:id>/', delete_student, name='delete_student'),
]


Import Django functions you need to build your views

1️⃣ render

  • Used to display HTML templates.

  • Example: render(request, 'home.html') shows the home.html page in the browser.


2️⃣ redirect

  • Used to send the user to another page after an action.

  • Example: redirect('students') sends the user to the students list page after registering.


3️⃣ get_object_or_404

  • Used to fetch a database object safely.

  • Example: student = get_object_or_404(Student, id=id)

  • If the student exists → returns it.

  • If not → shows a 404 error page automatically

  • Import your Student model from models.py

  • 4️⃣ from .models import Student

    • Imports your Student model from models.py.

    • Lets you create, read, update, and delete students in the database.

    VIEW FOR HOME 

    1️⃣ home(request)

    • Shows the home page.

    • Nothing dynamic here, just renders home.html.


    REGISTER VIEW 

    2️⃣ register(request)CREATE

    • If form is submitted (POST):

      • def register(request):

            if request.method == 'POST':

      • Gets fullname and course from the form.

      • GET THE DATA ENTER IN DATABASE 

    fullname = request.POST.get('fullname')
    course = request.POST.get('course')
      • Creates a new Student in the database.

    • Student.objects.create(
                  fullname=fullname,
                  course=course
      • Redirects to the students list page.

      • return redirect('students')


    • If form is not submitted (GET):

      • Just shows the registration form (register.html).

      •   return render(request, 'register.html')


    3️⃣ students(request)READ

    • Fetches all students from the database.

    • def students(request):
          students = Student.objects.all()
    • Passes them to students.html to display.

    • return render(request, 'students.html', {'students': students})

    • Handles the “list of students” page.

    • {'students': students}

      • This is a Python dictionary.

      • It passes data from your view to the template.

      • Key: 'students' → the name you use in the template

      • Value: students → the actual data (queryset from the database)


    4️⃣ edit_student(request, id)UPDATE

    • Finds a student by ID. If not found → 404 error.

    • def edit_student(request, id):
          student = get_object_or_404(Student, id=id)
    • If form submitted (POST):

      • if request.method == 'POST':
      • Updates fullname and course.

      • student.fullname = request.POST.get('fullname')
                student.course = request.POST.get('course')
      • Saves changes in the database.

      • student.save()

      • Redirects to students list.

    • return redirect('students')
    • If form not submitted (GET):

      • Shows form pre-filled with student’s current info (edit_student.html).

      • return render(request, 'edit_student.html', {'student': student})


    5️⃣ delete_student(request, id)DELETE

    • Finds a student by ID. If not found → 404 error.

    • def delete_student(request, id):
          student = get_object_or_404(Student, id=id)
    • Deletes the student from the database.

    • student.delete()
         
    • Redirects to the students list page.

    • return redirect('students')

    URL.PY 

    from django.contrib import admin
    from django.urls import path
    from pages.views import home, register, students, edit_student, delete_student

    urlpatterns = [
        path('admin/', admin.site.urls),
        path('', home, name='home'),
        path('register/', register, name='register'),
        path('students/', students, name='students'),
        path('edit/<int:id>/', edit_student, name='edit_student'),
        path('delete/<int:id>/', delete_student, name='delete_student'),
    ]


    from django.contrib import admin

    • Imports Django’s built-in admin site (where you can manage your models).

    2️⃣ from django.urls import path

    • Lets you define URL routes for your app.

    3️⃣ from pages.views import home, register, students, edit_student, delete_student

    • Imports all your view functions from pages/views.py so the URLs can point to them.

    1️⃣ path('admin/', admin.site.urls)

    • Opens Django’s built-in admin panel.

    • Visit /admin/ in the browser to manage your models.


    2️⃣ path('', home, name='home')

    • '' = empty string → this is the home page (/).

    • Runs the home view function.

    • name='home' → lets you refer to this URL in templates using {% url 'home' %}.


    3️⃣ path('register/', register, name='register')

    • /register/ → shows the student registration page.

    • Runs the register view.

    • name='register' → allows {% url 'register' %} in templates.


    4️⃣ path('students/', students, name='students')

    • /students/ → shows the list of all students.

    • Runs the students view.

    • name='students' → allows {% url 'students' %} in templates.


    5️⃣ path('edit/<int:id>/', edit_student, name='edit_student')

    • /edit/1/ → shows the edit page for student with id=1.

    • <int:id> → captures a number from the URL and passes it to edit_student(request, id).

    • name='edit_student' → use {% url 'edit_student' student.id %} in templates.


    6️⃣ path('delete/<int:id>/', delete_student, name='delete_student')

    • /delete/1/ → deletes the student with id=1.

    • <int:id> → passes the student’s id to delete_student(request, id).

    • name='delete_student' → use {% url 'delete_student' student.id %} in templates.


    EDIT_STUDENT 

    Table header

    <tr> <th>Full Name</th> <th>Course</th> <th>Action</th> </tr>
    • <tr> → table row

    • <th> → table header (column titles)

    • Creates three columns:

      1. Full Name – shows student name

      2. Course – shows student course

      3. Action – for Edit/Delete links


    2️⃣ Start of the loop

    {% for student in students %}
    • Loops through all students passed from your view

    • Each iteration sets student to one student object


    3️⃣ Table row for each student

    <tr> <td>{{ student.fullname }}</td> <td>{{ student.course }}</td> <td> <a href="{% url 'edit_student' student.id %}">Edit</a> | <a href="{% url 'delete_student' student.id %}" onclick="return confirm('Are you sure you want to delete this student?')"> Delete </a> </td> </tr>
    • <td> → table data cell

    • {{ student.fullname }} → shows the student’s full name

    • {{ student.course }} → shows the student’s course

    • <a href="{% url 'edit_student' student.id %}">Edit</a> → link to edit this student

    • <a href="{% url 'delete_student' student.id %}" ...>Delete</a> → link to delete this student

    • onclick="return confirm(...)" → shows a confirmation popup before deleting


    4️⃣ Empty list case

    {% empty %} <tr> <td colspan="3">No student registered yet</td> </tr> {% endfor %}
    • If there are no students in the database, this row shows:

      No student registered yet
    • colspan="3" → makes this message span all three columns


    5️⃣ Back Home link

    <br> <a href="{% url 'home' %}">Back Home</a>

    • Provides a link back to the home page using Django’s URL name

    • Safer than hardcoding / because if the URL changes, it still works














     

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