Session Overview

  • Edit Category
  • Updating Records
  • Edit Category Page
  • Delete Category
  • Delete Confirmation
  • Category CRUD Page

Edit Category

To edit a Category, we first retrieve the existing record from the database.

Retrieve Record
category = Category.objects.get(Id=id)

The retrieved object is passed to the Model Form using the instance parameter.

form = CategoryForm(instance=category)
Result: The form displays the existing Category values, allowing the user to modify them.
Understanding instance
instance = category

The instance parameter tells Django which record should be edited. Without it, Django creates a new record instead of updating the existing one.

Updating Records

After submitting the edited form, Django updates the existing record in the database.

Update View
def editCategory(request,id):

    category = Category.objects.get(Id=id)

    if request.method == "POST":

        form = CategoryForm(
            request.POST,
            instance=category
        )

        if form.is_valid():

            form.save()

            return redirect('categories')

    else:

        form = CategoryForm(
            instance=category
        )

    return render(
        request,
        "editcategory.html",
        {
            "form":form
        }
    )
Result: The selected Category is updated instead of creating a new record.

Edit Category Page

Create a template to display the Category Form with the existing data.

File Location
demo/templates/editcategory.html
editcategory.html
{% extends 'base.html' %}

{% block content %}

<div class="container mt-4">

    <h2>Edit Category</h2>

    <form method="post">

        {% csrf_token %}

        {{ form.as_p }}

        <button type="submit"
                class="btn btn-warning">

            Update

        </button>

    </form>

</div>

{% endblock %}
Result: The form displays the existing Category details. After clicking the Update button, the changes are saved to the database.

Delete Category

Django allows us to delete a record using the delete() method.

File Location
demo/views.py
Create Delete View
from django.shortcuts import redirect

from .models import Category

def deleteCategory(request,id):

    category = Category.objects.get(Id=id)

    category.delete()

    return redirect('categories')
Understanding the Code
Code Purpose
Category.objects.get() Retrieve Existing Record
delete() Delete Record
redirect() Return to Category List
Result: The selected Category is permanently removed from the database.
Understanding delete()
category.delete()

The delete() method permanently removes the selected record from the corresponding database table.

Delete Confirmation

Before deleting a record, it is recommended to ask the user for confirmation.

Delete Link
<a href="/deletecategory/{{ item.Id }}"
   onclick="return confirm('Are you sure you want to delete this category?')"
   class="btn btn-danger">

    Delete

</a>
Result: When the Delete button is clicked, a confirmation dialog is displayed. The record is deleted only if the user clicks OK.
Understanding confirm()
confirm("Are you sure?")

The JavaScript confirm() function displays a confirmation dialog.

User Action Result
OK Delete the Record
Cancel Stop the Delete Operation

Category CRUD Page

Now let us create a Category Management page where users can view, edit and delete records.

File Location
demo/templates/categories.html
categories.html
{% extends 'base.html' %}

{% block content %}

<div class="container mt-4">

    <h2>Category Management</h2>

    <a href="/createcategory/"
       class="btn btn-success mb-3">

        Add Category

    </a>

    <table class="table table-bordered table-striped">

        <thead>

            <tr>

                <th>Id</th>

                <th>Category Name</th>

                <th width="180">Action</th>

            </tr>

        </thead>

        <tbody>

        {% for item in categories %}

            <tr>

                <td>{{ item.Id }}</td>

                <td>{{ item.Name }}</td>

                <td>

                    <a href="/editcategory/{{ item.Id }}"
                       class="btn btn-warning btn-sm">

                        Edit

                    </a>

                    <a href="{% url 'deletecategory' item.Id %}"
                        class="btn btn-danger btn-sm"
                        onclick="return confirm('Are you sure you want to delete this category?')">

                            Delete

                </a>

                </td>

            </tr>

        {% endfor %}

        </tbody>

    </table>

</div>

{% endblock %}
Result: Users can now perform all Category operations from a single page.
Best Practice

Instead of hardcoding URLs, Django provides the {% url %} template tag.

{% url 'deletecategory' item.Id %}

If the URL pattern changes in the future, only urls.py needs to be updated. The template code remains unchanged.

Note: After creating new Views, we must register their URL patterns in urls.py. Otherwise, Django will return a 404 - Page Not Found error.
Example
path(
    'editcategory/<int:id>',
    views.editCategory,
    name='editcategory'
),

path(
    'deletecategory/<int:id>',
    views.deleteCategory,
    name='deletecategory'
),

Quick Revision

Edit Record
  • get()
  • instance
  • Pre-filled Form
Update Record
  • ModelForm
  • form.save()
  • redirect()
Delete Record
  • delete()
  • Confirmation
  • Redirect
CRUD Page
  • List Records
  • Edit Button
  • Delete Button
URLs
  • path()
  • Route Views
  • Named URLs
CRUD Methods
  • get()
  • save()
  • delete()
Important Methods
Category.objects.get()

CategoryForm(instance=category)

form.save()

category.delete()

redirect()
CRUD Flow
Select Record
      ↓
Edit Form
      ↓
Update Record
      ↓
Delete Record
      ↓
Category Management

Assignment

Complete the following tasks:
  1. Create a Product Model with the following fields:
    Name
    Price
    Unit
  2. Create and apply Migrations for the Product Model.
  3. Register the Product Model in the Django Admin Panel.
  4. Create a Model Form for the Product Model.
  5. Complete all CRUD Operations for Products:
    • Create Product
    • Display Product List
    • Edit Product
    • Delete Product
  6. Add Bootstrap styling to all Product pages.
  7. Display a confirmation dialog before deleting a Product.
  8. Register all required URL patterns in urls.py.