Weeks 13–14: Django Models
Chapter: Django Models – The Student Model
1. Introduction to Models
In Django, a **model** is a Python class that represents a **database table**. Each model defines the structure of data that will be stored in the database, including the fields (columns) and their types. Models are a core component of Django’s **Model-View-Template (MVT)** architecture and serve as the interface between the application and the database.
Django provides a module called `models` in `django.db`, which contains all the tools needed to create and manipulate database models.
2. Importing the Models Module
Before defining a model, it is necessary to import the `models` module:
```python
from django.db import models
```
* `from` → Python keyword used to import specific parts of a module.
* `django.db` → Django’s database package containing database-related tools.
* `import models` → Brings the `models` module into the current program, allowing access to fields and classes used to define database tables.
**Explanation:**
Without this import statement, Django will not recognize the model’s fields or provide the functionality needed to interact with the database.
3. Creating a Model Class**
A model is defined as a Python class that **inherits from `models.Model`**:
```python
class Student(models.Model):
```
* `class` → Python keyword used to define a class.
* `Student` → Name of the model class. This name typically represents the **concept or entity** the model stores.
* `(models.Model)` → Inheritance from Django’s base `Model` class, which provides the model with **CRUD capabilities** (Create, Read, Update, Delete) and integrates it with the database.
**Explanation:**
Inheritance allows the `Student` class to automatically gain the functionality needed to save, retrieve, update, and delete records in the database. Without inheriting from `models.Model`, the class would be a plain Python class with no database functionality.
4. Defining Fields
Each model consists of **fields**, which represent **columns in the database table**. The `Student` model has two fields:
```python
name = models.CharField(max_length=100)
age = models.IntegerField()
```
### **4.1 Name Field**
* `name` → The attribute representing the column name in the database.
* `models.CharField` → Field type used to store text data.
* `max_length=100` → Restricts the maximum number of characters to 100.
### **4.2 Age Field**
* `age` → The attribute representing the column name in the database.
* `models.IntegerField()` → Field type used to store whole numbers.
**Explanation:**
Fields define what kind of data can be stored in each column and are crucial for data validation. Django automatically converts these fields into the appropriate database column types.
---
## **5. Special Methods – `__str__()`**
```python
def __str__(self):
return self.name
```
* `def` → Python keyword for defining a function.
* `__str__()` → A special method that defines how the object is represented as a string.
* `self` → Refers to the current object of the class.
* `return self.name` → Returns the value of the `name` field when the object is displayed.
**Explanation:**
This method ensures that when a `Student` object is viewed in the Django admin panel or printed in the console, it displays the student’s name instead of a generic string like `Student object (1)`.
6. Mapping Models to the Database**
After defining the model, it must be **migrated to the database**. Django uses migrations to convert model definitions into database schema:
1. **Create migration files:**
```bash
python manage.py makemigrations
```
This generates migration scripts that describe the changes to be applied.
2. **Apply migrations:**
```bash
python manage.py migrate
```
This executes the migration scripts and creates the `Student` table in the database with the specified fields.
**Explanation:**
Migrations are Django’s way of synchronizing models with the database structure, ensuring consistency and integrity.
---
## **7. Best Practices**
* Use **meaningful names** for models and fields (`Student`, `name`, `age`).
* Always define `__str__()` for readability in admin and debugging.
* Choose **appropriate field types** for each type of data.
* Keep models **focused and simple** to avoid complexity.
* Use verbose names and help texts for clarity when needed.
---
## **8. Summary Diagram**
```
Class: Student (inherits models.Model)
├─ Field: name → CharField(max_length=100)
├─ Field: age → IntegerField()
└─ Method: __str__() → returns name
``
* **Class** → Represents a database table.
* **Fields** → Represent columns of the table.
* **Method** → Provides readable representation of objects.
## **Conclusion**
The `Student` model is a **simple yet powerful example** of a Django model. It introduces key concepts such as importing modules, defining classes and fields, using special methods, and integrating with the database through migrations. Understanding this model forms the foundation for building more complex Django applications.
CRUD SYSTEM
Day 1
What is CRUD?
Why CRUD is important
Example in Real Life
Example in Real Life
CRUD in Django – Steps
CRUD
What is CRUD?
CRUD is an acronym in computer science that stands for:
· C → Create: Add new data to a database.
· R → Read: View or retrieve data from a database.
· U → Update: Modify or edit existing data in the database.
· D → Delete: Remove data from the database.
In simple terms:
CRUD represents the four basic operations that you can perform on data in any system or application. Without CRUD, you cannot manage information effectively.
· Create → Add new records
· Read → See records
· Update → Change records
· Delete → Remove records
Why CRUD is important:
1. It allows applications to store and manage data.
2. It ensures that information is up-to-date and accurate.
3. It is the foundation of almost all database-driven applications (websites, apps, school systems, bank systems, etc.).
Example in Real Life:
Operation | Example |
Create | Register a new student in a school portal |
Read | View the student’s profile or grades |
Update | Correct the student’s address |
Delete | Remove a student who graduated or left school |
CRUD in Django – Steps
1. Install Python and Django
2. Create Django project and app
3. Create the model
4. Apply migrations
5. Create superuser for admin
6. Register model in admin
7. Create forms
8. Create views (Read, Create, Update, Delete)
9. Create templates (list, form, delete)
10. Configure URLs
11. Run the server
DAY 2:
Install Python and Django
Create Django Project and App
Registers the app with Django.
INSTALL PYTHON AND DJANGO
1. Install Python and Django
What it is:
This step is about setting up the programming environment so you can create and run Django applications.
· Python is the programming language that Django is built on.
· Django is the web framework that lets you build web applications quickly.
Why it is done:
· Django needs Python to work.
· Installing Django allows you to create projects, apps, and manage the database.
Basic Commands:
1. Check Python installation:
python --version(Ensure Python 3.x is installed)
INSTALL DJANGO
2. Install Django:
pip install django3. Check Django version:
django-admin –version
CREATE DJANGO PROJECT AND APP
Step 2: Create Django Project and App
Sets up the project structure and a functional app where you can start building your CRUD features.
2. Create Django Project and App
What it is:
· A project is the overall Django website/application.
· An app is a component inside the project that handles a specific functionality (like managing students).
Why it is done:
· The project organizes all your apps, settings, and configurations.
· Each app handles specific tasks, making your code organized and modular.
CREATE DJANGO PROJECT
Steps:
1. Create a new project:
django-admin startproject student_crudcd student_crud· startproject creates a new Django project folder.
· cd student_crud moves you into the project directory.
CREATE DJANGO APP
2. Create a new app:
python manage.py startapp students· startapp creates a new app folder inside the project.
· Here, the app will manage all student-related features.
REGISTERS THE APP WITH DJANGO
3. Add the app to settings.py:
INSTALLED_APPS = [ ..., 'students',]· Registers the app with Django.
· Without this, Django won’t know the app exists and won’t include it in the project.
DAY 3:
What Is The Meaning Of Create The Model
Why we create a model
Steps to Create a Model and Apply Migrations
STEP 3: CREATE THE MODEL:
It is the process of defining the structure of your data in Django by creating a model, which acts as a blueprint for a database table where records will be stored.
Why we create a model
· To define the structure of the data we want to store.
· To tell Django what fields each record should have.
· To allow Django to automatically create the database table.
· To enable CRUD operations on the data easily.
STEPS TO CREATE A MODEL AND APPLY MIGRATIONS
1. IMPORT DJANGO’S MODEL CLASSES SO YOU CAN DEFINE DATABASE TABLES AND FIELDS.
Code line: from django.db import models
What it is:
· This is a Python import statement used in Django.
· It allows you to use Django’s model system to define database tables (models) and their fields.
Why it’s used:
· Django provides a set of pre-built classes and tools for working with databases.
· models contains classes like CharField, IntegerField, DateField, etc.
· Without importing models, you cannot create tables or fields in Django.
Explanation word by word:
1. from
o Python keyword used to import specific modules or classes from a package.
o Here it says “get something from a package.”
2. django
o The Django web framework installed in your Python environment.
o All Django features are organized under the django package.
3. db
o Stands for database.
o django.db is the module in Django that handles database-related functionality.
4. import
o Python keyword used to bring in modules, classes, or functions so you can use them in your code.
5. models
o The module that contains classes for defining database tables (models) and fields.
o Examples: models.Model (base class for your tables), models.CharField (text field), models.IntegerField (number field).
2. CREATE A MODEL NAMED STUDENT THAT REPRESENTS A DATABASE TABLE.
This line says: “I am creating a table called Student in my database, and I want Django to handle it as a model so I can save, view, update, and delete students easily.”
Code line:
class Student(models.Model):
Student(models.Model):
Meaning:
Create a model named Student that represents a database table.
What it means:
· class:
o A Python keyword used to define a class, which is a blueprint for creating objects.
o In Django, a model is a class that describes a table in the database.
· Student:
o The name of the model.
o This will also be the name of the table (usually students_student) in the database unless you specify otherwise.
· (models.Model):
o Means the Student class inherits from Django’s Model class.
o models.Model gives your class all the functionality to interact with the database (save, read, update, delete records).
Why it’s done:
· To tell Django:
1. “This is a model for my app.”
2. “It should be treated as a table in the database.”
· Without inheriting from models.Model, Django won’t recognize it as a database table.
3. ADD A FIELD NAME TO STORE TEXT UP TO 100 CHARACTERS FOR EACH STUDENT.
This line says: “I want each student to have a name, which is text, and it cannot be longer than 100 characters.”
Code line:
name = models.CharField(max_length=100)
name = models.CharField(max_length=100)
Meaning:
Add a field name to store text up to 100 characters for each student.
What it means:
· name =
o This is the name of the field in the database and in your model.
o Each Student object will have a name value.
· models.CharField()
o CharField is a Django model class for text fields.
o It tells Django that this field will store string/text data.
· max_length=100
o Limits the maximum number of characters the field can hold to 100.
o Helps prevent errors and controls the size of data stored in the database.
Why it’s done:
· To define a column in the Student table that stores the name of each student.
· Without defining fields, the table would have no place to store data.
4. ADD A FIELD AGE TO STORE INTEGER NUMBERS FOR EACH STUDENT.
This line says: “I want each student to have an age, which must be a whole number.”
Code line:
age = models.IntegerField()
age = models.IntegerField()
Meaning:
Add a field age to store numbers (integers) for each student.
What it means:
· age =
o The name of the field in the database and in the model.
o Each Student object will have an age value.
· models.IntegerField()
o IntegerField is a Django model class for numbers.
o It tells Django that this field will store integer values only (whole numbers).
Why it’s done:
· To define a column in the Student table that stores the age of each student.
· Without defining fields, the table would have no place to store data.
Common Django Model Fields
1. CharField – Stores text (string) up to a max length.
2. TextField – Stores long text (no max length limit).
3. IntegerField – Stores whole numbers.
4. FloatField – Stores decimal numbers (e.g., 3.14).
5. BooleanField – Stores True/False values.
6. DateField – Stores a date (year, month, day).
7. DateTimeField – Stores date and time.
8. EmailField – Stores email addresses (validates format).
9. URLField – Stores website URLs (validates format).
10. DecimalField – Stores fixed-point decimal numbers (useful for money).
11. TimeField – Stores time only (hours, minutes, seconds).
12. FileField – Stores a file upload path.
13. ImageField – Stores an image upload path (requires Pillow library).
14. ForeignKey – Creates a relationship to another model (many-to-one).
15. ManyToManyField – Creates a many-to-many relationship between models.
16. OneToOneField – Creates a one-to-one relationship between models.
5. DEFINE HOW THE STUDENT OBJECT WILL BE DISPLAYED IN THE ADMIN PANEL OR SHELL.
When I look at a student in the admin panel or console, show the name of the student instead of just a code or number.
Code lines:
def __str__(self): return self.name
__str__(self): return self.name
Meaning:
Define how the student object will be displayed in the admin panel or shell.
What it means:
· def str(self):
o def → Defines a function or method in Python.
o __str__ → A special method in Python that tells the system how to represent the object as a string.
o self → Refers to the current instance of the object (a specific student).
· return self.name
o When Django displays the student object (in admin or shell), it will show the student’s name instead of something generic like <Student object (1)>.
Why it’s done:
· Makes it easy to identify objects when you have multiple students.
· Improves readability in the admin panel, shell, and debugging.
· Without it, Django shows ugly default object names which are hard to understand.
6. CREATE A MIGRATION FILE BASED ON YOUR MODEL, PREPARING THE DATABASE CHANGES.
This command says: “Look at my model definitions and create a plan for how to update the database to match them.”
Command:
python manage.py makemigrations
python manage.py makemigrations
Meaning:
Create a migration file based on your model, preparing the database changes.
What it means:
· python manage.py → Tells Python to run a Django management command.
· makemigrations → Tells Django:
o “Look at my models and see what has changed.”
o Create a migration file (a blueprint of changes) that describes how the database should be updated.
· Migration file → A file Django uses to keep track of changes to your models.
o It doesn’t change the database yet.
o It just prepares the instructions to apply later.
Why it’s done:
· Keeps your database in sync with your models.
· Allows Django to track changes to tables over time.
· Helps avoid manual database updates (you don’t have to write SQL).
7. APPLY THE MIGRATION TO ACTUALLY CREATE THE STUDENT TABLE IN THE DATABASE.
“Now actually make the Student table in the database so I can start saving student data.”
Command:
python manage.py migrate
python manage.py migrate
Meaning:
Apply the migration to actually create the Student table in the database.
What it means:
· python manage.py → Runs a Django management command.
· migrate → Tells Django:
o “Take all the prepared migration files and apply them to the database.”
o This creates tables, columns, and relationships in the database according to your models.
· Result:
o The Student table is now created in the database.
o Django keeps track of applied migrations so it knows which changes are already done.
Why it’s done:
· To turn your model definitions into actual database tables.
· Without this step, your database would not store any data.
· Ensures your database matches your models exactly.
Step 3: Create the Model
- In students/models.py, define the student model:
from django.db import models
class Student(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
def __str__(self):
return self.name
- Apply migrations:
python manage.py makemigrations
python manage.py migrate
DAY 4:
WHAT IS SUPERUSER
Why it’s done:
Steps Only:
Step 4: Create Superuser for Admin
What it is:
· Creating a superuser is making an administrator account for your Django project.
· This user can log in to the Django admin panel and manage all data (add, view, update, delete records).
Why it’s done:
· To access and manage your database tables through Django’s built-in admin interface.
· To perform CRUD operations easily without writing code.
· To securely control who can make changes to your app data.
Steps Only:
1. Run command:
python manage.py createsuperuser Explanation word by word:
1. python
o Runs the Python interpreter.
o Ensures the command uses your installed Python environment.
2. manage.py
o Django’s command-line utility for managing your project.
o It provides built-in commands like runserver, makemigrations, migrate, and createsuperuser.
3. createsuperuser
o The specific command that tells Django:
§ “Create an admin account with full access to the admin panel.”
o You will be asked to provide username, email, and password for this superuser.
2. Enter a username.
3. Enter an email address.
4. Enter a password.
5. Access the admin panel at:
http://127.0.0.1:8000/admin/
Step 4: Create Superuser for Admin
python manage.py createsuperuser
- Enter username, email, and password.
- Access admin panel at http://127.0.0.1:8000/admin/.
DAY 5:
WHAT IS THE MEANING OF REGISTER MODEL IN ADMIN
Why it’s done:
Code Explanation Line by Line:
Step 5: Register Model in Admin
What it is:
· Registering a model in the admin panel makes it visible and manageable in Django’s admin interface.
· Without registering, the model exists in your database but cannot be accessed or edited through the admin panel.
Why it’s done:
· To enable CRUD operations (Create, Read, Update, Delete) on the model through the admin panel.
· To manage data easily without writing Python code.
· To allow superusers to view and maintain records conveniently.
Code Explanation Line by Line:
from django.contrib import admin
django.contrib import admin· Imports Django’s admin module, which provides tools to manage models in the admin interface.
from .models import Student· Imports the Student model you created so you can register it in the admin.
admin.site.register(Student)· Registers the Student model with the admin site.
· After this, the Student model will appear in the Django admin panel, allowing superusers to manage student records.
Step 5: Register Model in Admin
In students/admin.py:
from django.contrib import admin
from .models import Student
admin.site.register(Student)
Step 6: Create Forms
Meaning:
Create a form in Django to allow users to input or edit student data (name and age) in a web interface.
In beginner-friendly terms:
This code says: “Create a form that matches my Student table so users can fill in the student’s name and age, and Django will save it automatically in the database.”
Step-by-step Explanation:
1. from django import forms
· What it is: Imports Django’s form module, which helps create forms in HTML automatically.
· Why: Forms are needed to take user input and validate it before saving to the database.
· In simple terms: “I want to use Django’s tools to make input forms for my website.”
2. from .models import Student
· What it is: Imports the Student model from your app.
· Why: The form will be linked to the Student table, so input data can be saved directly.
· In simple terms: “I want this form to save data into the Student table.”
3. class StudentForm(forms.ModelForm):
· What it is: Defines a new form class named StudentForm.
· forms.ModelForm → A special Django class that creates a form based on a model.
· Why: Using ModelForm automatically generates fields in the form based on your model fields, so you don’t have to write HTML manually.
· In simple terms: “Make a form that automatically matches the Student model.”
4. class Meta:
· What it is: An inner class in Django used to configure the form.
· Why: Tells Django which model to use and which fields to include in the form.
· In simple terms: “This section defines the settings for the form.”
5. model = Student
· What it is: Specifies that this form is linked to the Student model.
· Why: So the form knows where to save the input data.
· In simple terms: “This form will add/edit data in the Student table.”
6. fields = ['name', 'age']
· What it is: Lists the fields from the model that should appear in the form.
· Why: Only these fields will be shown for input; other fields (if any) are ignored.
· In simple terms: “The form will let users enter the name and age of a student.”
Why this step is done:
· To allow users to add or edit data via a web form.
· To validate input automatically (e.g., text for name, numbers for age).
· To connect the form directly to the database, making CRUD operations easier.
Step 6: Create Forms
In students/forms.py:
from django import forms
from .models import Student
class StudentForm(forms.ModelForm):
class Meta:
model = Student
fields = ['name', 'age']
Step 7: Create Views
Create Views in Django
What it is:
· A view is a Python function (or class) in Django that handles a user’s request and returns a response.
· Create Views are specific views that handle the creation of new data in the database.
· In CRUD, the “C” (Create) operation is handled by a Create View.
Why it’s used:
· To allow users to add new records to the database via a form on a webpage.
· To validate input before saving data.
· To connect forms and models so data is stored automatically.
· Without a Create View, users would not have a way to add data from the web interface.
How it works (in simple terms):
1. The user opens a page (e.g., “Add Student”).
2. Django calls the Create View function.
3. The view displays a form (StudentForm) to the user.
4. The user fills out the form and submits it.
5. The view validates the input.
6. If valid, the view saves the data to the database and redirects the user to another page (like the student list).
IMPORT THE TOOLS AND CLASSES NEEDED TO HANDLE HTTP REQUESTS
Code:
from django.shortcuts import render, redirect, get_object_or_404from .models import Studentfrom .forms import StudentForm
django.shortcuts import render, redirect, get_object_or_404 .models import Student .forms import StudentForm
Step-by-step Explanation:
1. from django.shortcuts import render, redirect, get_object_or_404
· What it is: Imports Django functions that help your views handle web requests and responses.
· Explanation of each function:
o render → Displays an HTML template with data.
§ Example: Show a list of students in a webpage.
o redirect → Sends the user to another page after an action.
§ Example: After adding a student, redirect to the student list page.
o get_object_or_404 → Retrieves a database object or shows a 404 error if it doesn’t exist.
§ Example: Find a student by ID for editing; if not found, show “Page not found.”
· Why it’s done:
o These are essential for handling CRUD operations in Django views.
· In beginner-friendly terms:
“Bring tools that let me show pages, move users to another page, and safely get data from the database.”
2. from .models import Student
· What it is: Imports the Student model from your app.
· Why it’s done: So views can read, create, update, and delete student records.
· Beginner-friendly: “I want my view to access the Student table in the database.”
3. from .forms import StudentForm
· What it is: Imports the StudentForm you created in forms.py.
· Why it’s done: So views can display the form, validate user input, and save data to the database.
· Beginner-friendly: “I want my view to use the form that lets users add or edit students.”
VIEW RETRIEVES ALL STUDENT RECORDS
This function gets all the students from the database and shows them on the webpage student_list.html.
Code:
# Read - List all studentsdef student_list(request): students = Student.objects.all() return render(request, 'students/student_list.html', {'students': students})
student_list(request): students = Student.objects.all() return render(request, 'students/student_list.html', {'students': students})
Meaning:
This view retrieves all student records from the database and displays them on a webpage.
Step-by-step Explanation:
1. # Read - List all students
· What it is: A comment describing what the function does.
· Why it’s done: Makes the code easy to understand for you or other developers.
· Beginner-friendly: “This function shows all students in the database.”
2. def student_list(request):
· What it is: Defines a view function named student_list.
· request → Represents the user’s request to the server (like opening a webpage).
· Why it’s done: Every view needs a function to handle a request and return a response.
· Beginner-friendly: “When a user opens the student list page, this function runs.”
3. students = Student.objects.all()
· What it is: Queries the database to get all records from the Student table.
· Explanation:
o Student.objects → Access all student objects in the database.
o .all() → Returns all the student records as a list.
· Why it’s done: To have all student data available to show on the webpage.
· Beginner-friendly: “Get all students from the database so I can show them on the page.”
4. return render(request, 'students/student_list.html', {'students': students})
· What it is: Sends a response back to the user with an HTML page.
· Explanation:
o render() → Combines a template with data to display a webpage.
o 'students/student_list.html' → The HTML template that shows the student list.
o {'students': students} → A dictionary sending the student data to the template.
· Why it’s done: So the template can loop through the students and display them on the page.
· Beginner-friendly: “Show the student list page and fill it with all the students from the database.”
Code:
# Create - Add a new studentdef student_create(request): form = StudentForm(request.POST or None) if form.is_valid(): form.save()
return redirect('student_list') return render(request, 'students/student_form.html', {'form': form})
student_create(request): form = StudentForm(request.POST or None) if form.is_valid(): form.save() return redirect('student_list') return render(request, 'students/student_form.html', {'form': form})
In beginner-friendly summary:
This view shows a form to add a new student. It checks if the user input is valid, saves it to the database, and then redirects the user to the list of all students.
Meaning:
This view displays a form to add a new student, validates the input, saves the student to the database, and redirects to the student list page.
Step-by-step Explanation:
1. # Create - Add a new student
· What it is: A comment describing the purpose of the function.
· Why: Helps others (or you) understand the code.
· Beginner-friendly: “This function adds a new student to the database.”
2. def student_create(request):
· What it is: Defines a view function called student_create.
· request → Represents the user’s request (like opening the add student page or submitting the form).
· Why: Every view function needs a request parameter to handle user actions.
· Beginner-friendly: “This function runs when the user visits the add student page.”
3. form = StudentForm(request.POST or None)
· What it is: Creates an instance of StudentForm.
· Explanation:
o request.POST → Contains form data submitted by the user.
o or None → If the page is opened for the first time, the form will be empty.
· Why: So the form can either show empty fields or process submitted data.
· Beginner-friendly: “Show a blank form, or fill it with what the user submitted.”
4. if form.is_valid():
· What it is: Checks if the form input follows the rules defined in the model.
· Why: Prevents invalid data from being saved (like empty name or non-numeric age).
· Beginner-friendly: “Check if the user filled the form correctly.”
5. form.save()
· What it is: Saves the new student data to the database.
· Why: This is the Create operation in CRUD.
· Beginner-friendly: “Add the new student to the database.”
6. return redirect('student_list')
· What it is: Redirects the user to the student list page after saving.
· Why: To show the updated list of students.
· Beginner-friendly: “After adding a student, go back to the list of students.”
7. return render(request, 'students/student_form.html', {'form': form})
· What it is: Shows the form on the webpage.
· Explanation:
o students/student_form.html → Template that displays the form.
o {'form': form} → Sends the form instance to the template so fields can be rendered.
· Why: If the page is loaded for the first time or the form has errors, the user sees the form.
· Beginner-friendly: “Show the form to the user so they can add a new student.”
Code:
# Update - Edit student detailsdef student_update(request, pk): student = get_object_or_404(Student, pk=pk)
form = StudentForm(request.POST or None, instance=student) if form.is_valid(): form.save()
return redirect('student_list') return render(request, 'students/student_form.html', {'form': form})
student_update(request, pk): student = get_object_or_404(Student, pk=pk) form = StudentForm(request.POST or None, instance=student) if form.is_valid(): form.save() return redirect('student_list') return render(request, 'students/student_form.html', {'form': form})
Meaning:
This view allows users to edit existing student data, validate it, save changes to the database, and redirect to the student list page.
Step-by-step Explanation:
1. # Update - Edit student details
· What it is: A comment explaining the function’s purpose.
· Why: Helps you or others understand what the code does.
· Beginner-friendly: “This function edits details of a student in the database.”
2. def student_update(request, pk):
· What it is: Defines a view function called student_update.
· request → Represents the user’s HTTP request (like opening the edit page or submitting the form).
· pk → Primary key of the student being edited (unique ID).
· Why: Needed to identify which student to update.
· Beginner-friendly: “This function runs when the user wants to edit a specific student.”
3. student = get_object_or_404(Student, pk=pk)
· What it is: Retrieves the student from the database by its primary key (pk).
· get_object_or_404 → Returns the student if found, otherwise shows a 404 error page.
· Why: Ensures the student exists before editing.
· Beginner-friendly: “Find the student to edit, or show a ‘not found’ page if it doesn’t exist.”
4. form = StudentForm(request.POST or None, instance=student)
· What it is: Creates a form instance for editing.
· request.POST or None → Uses submitted data if the form was posted, otherwise empty.
· instance=student → Links the form to the existing student record.
· Why: Pre-fills the form with current student data so the user can edit it.
· Beginner-friendly: “Show a form with the student’s current info so the user can change it.”
5. if form.is_valid():
· What it is: Checks if the edited form input is valid.
· Why: Prevents invalid data from being saved.
· Beginner-friendly: “Check that the user entered correct values before saving.”
6. form.save()
· What it is: Saves the updated student data to the database.
· Why: This completes the Update operation in CRUD.
· Beginner-friendly: “Save the changes to the student in the database.”
7. return redirect('student_list')
· What it is: Redirects the user to the student list page after updating.
· Why: Lets the user see the updated list immediately.
· Beginner-friendly: “After updating, go back to the list of students.”
8. return render(request, 'students/student_form.html', {'form': form})
· What it is: Shows the form again (with current data or errors).
· Why: If the form is loaded for the first time or has errors, the user can edit it.
· Beginner-friendly: “Show the edit form to the user so they can make changes.”
In beginner-friendly summary:
This view loads a form with the student’s current data, allows the user to edit it, validates the input, saves the changes to the database, and redirects back to the student list.
Code:
# Delete - Remove studentdef student_delete(request, pk): student = get_object_or_404(Student, pk=pk)
if request.method == 'POST': student.delete()
return redirect('student_list') return render(request, 'students/student_delete.html', {'student': student})
student_delete(request, pk): student = get_object_or_404(Student, pk=pk) if request.method == 'POST': student.delete() return redirect('student_list') return render(request, 'students/student_delete.html', {'student': student})
Meaning:
This view allows users to delete a student record from the database after confirming the action.
Step-by-step Explanation:
1. # Delete - Remove student
· What it is: A comment describing the function’s purpose.
· Why: Helps you or others understand the code.
· Beginner-friendly: “This function deletes a student from the database.”
2. def student_delete(request, pk):
· What it is: Defines a view function named student_delete.
· request → Represents the user’s HTTP request (opening the delete page or submitting the delete confirmation).
· pk → Primary key (unique ID) of the student to delete.
· Why: Needed to identify which student to remove.
· Beginner-friendly: “This function runs when the user wants to delete a specific student.”
3. student = get_object_or_404(Student, pk=pk)
· What it is: Retrieves the student from the database by its primary key (pk).
· get_object_or_404 → Returns the student if found, otherwise shows a 404 error page.
· Why: Ensures the student exists before attempting to delete.
· Beginner-friendly: “Find the student to delete, or show a ‘not found’ page if it doesn’t exist.”
4. if request.method == 'POST':
· What it is: Checks if the delete confirmation form was submitted.
· Why: Prevents accidental deletion when the page is just loaded (GET request).
· Beginner-friendly: “Only delete the student if the user confirmed it.”
5. student.delete()
· What it is: Deletes the student record from the database.
· Why: This completes the Delete operation in CRUD.
· Beginner-friendly: “Remove the student from the database.”
6. return redirect('student_list')
· What it is: Redirects the user to the student list page after deletion.
· Why: Lets the user see the updated list without the deleted student.
· Beginner-friendly: “After deleting, go back to the list of students.”
7. return render(request, 'students/student_delete.html', {'student': student})
· What it is: Displays a confirmation page asking the user if they are sure about deleting the student.
· students/student_delete.html → Template that shows the confirmation message.
· {'student': student} → Passes the student’s information to the template.
· Why: Ensures the user doesn’t accidentally delete a student.
· Beginner-friendly: “Show a page asking the user: ‘Are you sure you want to delete this student?’”
In beginner-friendly summary:
This view shows a confirmation page to delete a student. If the user confirms (submits the form), the student is removed from the database and the user is redirected to the student list.
Step 7: Create Views
In students/views.py:
from django.shortcuts import render, redirect, get_object_or_404
from .models import Student
from .forms import StudentForm
# Read - List all students
def student_list(request):
students = Student.objects.all()
return render(request, 'students/student_list.html', {'students': students})
# Create - Add a new student
def student_create(request):
form = StudentForm(request.POST or None)
if form.is_valid():
form.save()
return redirect('student_list')
return render(request, 'students/student_form.html', {'form': form})
# Update - Edit student details
def student_update(request, pk):
student = get_object_or_404(Student, pk=pk)
form = StudentForm(request.POST or None, instance=student)
if form.is_valid():
form.save()
return redirect('student_list')
return render(request, 'students/student_form.html', {'form': form})
# Delete - Remove student
def student_delete(request, pk):
student = get_object_or_404(Student, pk=pk)
if request.method == 'POST':
student.delete()
return redirect('student_list')
return render(request, 'students/student_delete.html', {'student': student})
student_list.html
What it is:
This template displays a list of students and provides links to add, edit, or delete a student.
Step-by-step Explanation:
1. 1. Create folder students/templates/students/
· What it is: Folder structure to store templates for the students app.
· Why: Django looks in the templates folder for HTML files to render.
· Beginner-friendly: “Make a folder to keep all HTML pages for students.”
2. <h1>Students</h1>
· What it is: HTML heading that displays the title “Students”.
· Why: Shows the page heading so users know what the page is.
· Beginner-friendly: “Display the title of the page.”
3. <a href="{% url 'student_create' %}">Add Student</a>
· What it is: HTML link that points to the Add Student page.
· {% url 'student_create' %} → Django template tag that generates the URL for the student_create view.
· Why: Lets the user navigate to the page for creating a new student.
· Beginner-friendly: “Add a clickable link to go to the page where you can add a new student.”
4. <ul> … </ul>
· What it is: An HTML unordered list to display all students.
· Why: Lists all students neatly on the page.
· Beginner-friendly: “Start a list to show each student.”
5. {% for student in students %} … {% endfor %}
· What it is: Django template loop to go through all students passed from the view.
· Why: Displays each student from the database dynamically.
· Beginner-friendly: “For each student in the list, show their name, age, and options.”
6. <li>{{ student.name }} ({{ student.age }})
· What it is: HTML list item displaying the student’s name and age.
· {{ student.name }} / {{ student.age }} → Django template variables showing data from the database.
· Why: Lets users see each student’s information.
· Beginner-friendly: “Show the student’s name and age in the list.”
7. <a href="{% url 'student_update' student.id %}">Edit</a>
· What it is: Link to edit the specific student.
· {% url 'student_update' student.id %} → Generates the URL for editing this student using their ID.
· Why: Allows the user to update student details.
· Beginner-friendly: “Click here to change this student’s information.”
8. <a href="{% url 'student_delete' student.id %}">Delete</a>
· What it is: Link to delete the specific student.
· {% url 'student_delete' student.id %} → Generates the URL for deleting this student using their ID.
· Why: Lets the user remove a student from the database.
· Beginner-friendly: “Click here to remove this student.”
In beginner-friendly summary:
This template shows all students in a list, with options to add new students, edit existing ones, or delete them. The page automatically gets data from the database and generates links for each action.
What it is:
This template displays a form for adding or updating a student. It shows input fields, handles user submission, and protects against security issues.
Step-by-step Explanation:
1. <h1>Student Form</h1>
· What it is: HTML heading that shows “Student Form” at the top of the page.
· Why: Lets users know that this page is for adding or editing a student.
· Beginner-friendly: “Display the title of the page so the user knows it’s a student form.”
2. <form method="post">
· What it is: HTML form element that sends data to the server.
· method="post" → Specifies that the form will send data securely instead of putting it in the URL.
· Why: POST is used for sending data that will create or update records in the database.
· Beginner-friendly: “Start a form that sends the user’s input to the server to save it.”
3. {% csrf_token %}
· What it is: Django template tag for security.
· Why: Prevents Cross-Site Request Forgery (CSRF) attacks, ensuring only your website can submit the form.
· Beginner-friendly: “Add a secret code so no one else can submit fake forms on your website.”
4. {{ form.as_p }}
· What it is: Displays the Django form fields as paragraphs.
· Explanation:
o form → The form instance sent from the view (StudentForm).
o .as_p → Renders each field inside a <p> tag.
· Why: Makes the form look neat and automatically generates input fields for name and age.
· Beginner-friendly: “Show the form fields for the user to type the student’s name and age.”
5. <button type="submit">Save</button>
· What it is: Button to submit the form.
· Why: Sends the user input to the server to be processed by the view.
· Beginner-friendly: “Click this button to save the student information.”
6. </form>
· What it is: Closes the form element.
· Why: Marks the end of the form in HTML.
· Beginner-friendly: “End the form here.”
In beginner-friendly summary:
This template shows a form for adding or editing a student, with fields for name and age. It includes a security token, automatically displays the fields, and has a submit button to save the data.
What it is:
This template displays a confirmation page for deleting a student. It asks the user if they are sure and provides a button to perform the deletion.
Step-by-step Explanation:
1. <h1>Delete Student</h1>
· What it is: HTML heading that shows the title “Delete Student” at the top of the page.
· Why: Lets users know that this page is specifically for deleting a student.
· Beginner-friendly: “Show a clear title so the user knows this page is for deleting a student.”
2. <p>Are you sure you want to delete {{ student.name }}?</p>
· What it is: Paragraph that asks the user for confirmation.
· {{ student.name }} → Shows the name of the student being deleted dynamically from the database.
· Why: Prevents accidental deletion by letting the user see which student will be removed.
· Beginner-friendly: “Ask the user if they really want to delete this student and show the student’s name.”
3. <form method="post">
· What it is: HTML form that submits the deletion request to the server.
· method="post" → Ensures the deletion request is sent securely instead of using GET.
· Why: POST is used for making changes to the database (like deleting records).
· Beginner-friendly: “Start a form to send the delete request to the server.”
4. {% csrf_token %}
· What it is: Django security tag to prevent Cross-Site Request Forgery (CSRF).
· Why: Ensures that only your website can submit the delete request, preventing malicious attacks.
· Beginner-friendly: “Add a security token so the delete request is safe.”
5. <button type="submit">Yes, Delete</button>
· What it is: Button that confirms deletion and submits the form.
· Why: When clicked, the student_delete view is triggered to remove the student from the database.
· Beginner-friendly: “Click this button if you want to delete the student.”
6. </form>
· What it is: Closes the form element.
· Why: Marks the end of the delete confirmation form.
· Beginner-friendly: “End the delete form here.”
In beginner-friendly summary:
This template asks the user if they are sure they want to delete a student, shows the student’s name, and provides a submit button to confirm deletion. It uses a secure POST method with a CSRF token to safely remove the student from the database.
Step 8: Create Templates
- Create folder students/templates/students/.
- student_list.html
<h1>Students</h1>
<a href="{% url 'student_create' %}">Add Student</a>
<ul>
{% for student in students %}
<li>{{ student.name }} ({{ student.age }})
<a href="{% url 'student_update' student.id %}">Edit</a>
<a href="{% url 'student_delete' student.id %}">Delete</a>
</li>
{% endfor %}
</ul>
- student_form.html
<h1>Student Form</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Save</button>
</form>
- student_delete.html
<h1>Delete Student</h1>
<p>Are you sure you want to delete {{ student.name }}?</p>
<form method="post">
{% csrf_token %}
<button type="submit">Yes, Delete</button>
</form>
Step 9: Configure URLs
Meaning:
This file defines the URL patterns for the students app, mapping URLs to their corresponding views.
Step-by-step Explanation:
1. from django.urls import path
· What it is: Imports Django’s path function to define URLs.
· Why: Needed to tell Django which URL points to which view.
· Beginner-friendly: “Bring in the tool to create website links for your pages.”
2. from . import views
· What it is: Imports all views from the current app (students).
· Why: So we can connect URLs to the functions that handle them.
· Beginner-friendly: “Bring in the code that does the work when a page is opened.”
3. urlpatterns = [...]
· What it is: A list of URL patterns that maps URLs to views.
· Why: Django checks this list to know which page to show for each URL.
· Beginner-friendly: “Make a list of links and tell Django what each link should do.”
4. path('', views.student_list, name='student_list')
· What it is: Maps the home page of the app ('') to the student_list view.
· name='student_list' → Gives a name to the URL for easy reference in templates.
· Beginner-friendly: “When the user visits the home page of students, show the student list.”
5. path('create/', views.student_create, name='student_create')
· What it is: Maps /create/ URL to the student_create view.
· Beginner-friendly: “When the user goes to /create/, show the page to add a new student.”
6. path('update/<int:pk>/', views.student_update, name='student_update')
· What it is: Maps URLs like /update/1/ to the student_update view.
· <int:pk> → Captures the student’s ID from the URL and passes it to the view.
· Beginner-friendly: “When the user wants to edit a student, Django uses the student’s ID to find them.”
7. path('delete/<int:pk>/', views.student_delete, name='student_delete')
· What it is: Maps URLs like /delete/1/ to the student_delete view.
· Beginner-friendly: “When the user wants to delete a student, Django uses the student’s ID to remove them.”
2. Main project URLs (student_crud/urls.py)
Code:
from django.contrib import adminfrom django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls), path('', include('students.urls')),]
django.contrib import admin django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('students.urls')),]
Meaning:
This file defines the main URL routes for the entire project and includes app-specific URLs.
Step-by-step Explanation:
1. from django.contrib import admin
· What it is: Imports Django’s admin module.
· Why: Needed to access the admin panel.
· Beginner-friendly: “Bring in the tool to manage the database through a web page.”
2. from django.urls import path, include
· What it is: Imports path for URL definitions and include to include URLs from apps.
· Beginner-friendly: “Bring in the tools to make website links and include app links.”
3. urlpatterns = [...]
· What it is: Main list of project URL patterns.
· Why: Tells Django which URLs belong to admin and which to apps.
4. path('admin/', admin.site.urls)
· What it is: Maps /admin/ URL to Django’s admin panel.
· Beginner-friendly: “Visit /admin/ to manage the site and database.”
5. path('', include('students.urls'))
· What it is: Includes all URLs defined in the students app for the home page.
· Beginner-friendly: “Use all the links from the students app for the main site.”
In beginner-friendly summary:
The URLs configuration connects user-accessible links to the correct views. The students/urls.py handles app-specific URLs like listing, adding, editing, or deleting students, while student_crud/urls.py includes the app URLs and the admin panel route.
Step 9: Configure URLs
- In students/urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('', views.student_list, name='student_list'),
path('create/', views.student_create, name='student_create'),
path('update/<int:pk>/', views.student_update, name='student_update'),
path('delete/<int:pk>/', views.student_delete, name='student_delete'),
]
- Include app URLs in main student_crud/urls.py:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('students.urls')),
]
Step 10: Run the Server
python manage.py runserver
- Open browser: http://127.0.0.1:8000/
- You can now Add, View, Update, and Delete students.
✅ Step 11: Optional Enhancements
- Add search functionality
- Add student grades
- Style pages with Bootstrap or CSS
- Add pagination for many students


0 comments:
Post a Comment