Django Class Based Views
×


Django Class Based Views

488

Introduction

In this tutorial, we'll learn how to implement CRUD operations — Create, Retrieve, Update, and Delete — in Django using Class-Based Generic Views. These views offer a clean and efficient way to handle common web application patterns, reducing boilerplate code and improving maintainability.

Prerequisites

Before we begin, ensure you have Django installed and a basic understanding of Django projects, apps, and models. Familiarity with Python and HTML will help you follow along better.

Creating a Django Project and App

Start by setting up a Django project and app if you haven't already:

django-admin startproject myproject
cd myproject
python manage.py startapp myapp

Add the new app to INSTALLED_APPS inside settings.py:

INSTALLED_APPS = [
    ...
    'myapp',
]

Defining the Model

Let’s define a simple Book model inside models.py:

from django.db import models

class Book(models.Model):
    title = models.CharField(max_length=200)
    author = models.CharField(max_length=100)
    published_date = models.DateField()

    def __str__(self):
        return self.title

Run migrations to create the corresponding database table:

python manage.py makemigrations
python manage.py migrate

Using Class-Based Generic Views for CRUD

Django provides built-in generic views that simplify CRUD operations. Let's use them for our Book model.

Create View

from django.urls import reverse_lazy
from django.views.generic.edit import CreateView
from .models import Book

class BookCreateView(CreateView):
    model = Book
    fields = ['title', 'author', 'published_date']
    template_name = 'myapp/book_form.html'
    success_url = reverse_lazy('book-list')

Retrieve/List View

from django.views.generic.list import ListView

class BookListView(ListView):
    model = Book
    template_name = 'myapp/book_list.html'
    context_object_name = 'books'

Update View

from django.views.generic.edit import UpdateView

class BookUpdateView(UpdateView):
    model = Book
    fields = ['title', 'author', 'published_date']
    template_name = 'myapp/book_form.html'
    success_url = reverse_lazy('book-list')

Delete View

from django.views.generic.edit import DeleteView

class BookDeleteView(DeleteView):
    model = Book
    template_name = 'myapp/book_confirm_delete.html'
    success_url = reverse_lazy('book-list')

Configuring URLs

Set up your URL routes in urls.py of your app to connect these views:

from django.urls import path
from .views import BookListView, BookCreateView, BookUpdateView, BookDeleteView

urlpatterns = [
    path('', BookListView.as_view(), name='book-list'),
    path('create/', BookCreateView.as_view(), name='book-create'),
    path('update/<int:pk>/', BookUpdateView.as_view(), name='book-update'),
    path('delete/<int:pk>/', BookDeleteView.as_view(), name='book-delete'),
]

Templates

Create the following templates inside myapp/templates/myapp/ to render the views:

  • book_list.html: Display the list of books with options to add, edit, or delete.
  • book_form.html: Used for both creating and updating a book.
  • book_confirm_delete.html: Confirmation page before deleting a book.

Running the Application

Start the development server:

python manage.py runserver

Open your browser and visit http://127.0.0.1:8000/ to interact with your CRUD app powered by class-based generic views.

Conclusion

Class-Based Generic Views in Django offer a concise and elegant way to implement CRUD functionality with less repetitive code. They improve readability and maintainability, making them ideal for both beginners and experienced developers. As you become comfortable, you can customize these views further to fit complex requirements.



If you’re passionate about building a successful blogging website, check out this helpful guide at Coding Tag – How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!

For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!



Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments

Coding Tag WhatsApp Chat