Django CRUD Operation Using Class-Based Views Example

Hey Friends,
In this tute, we will discuss django python crud operation using class-based views. let’s discuss about django python crud operation using class-based views app. I’m going to show you about django crud operation using class-based views example. you can see crud operations using class based views in django. You just need to some step to done class based views django python example.
So, class based generic views are advanced set of built-in views which are used for implementation of selective view strategies such as create, retrieve, update, delete.
- CreateView :create or add new entries in a table in the database.
- Retrieve Views :read, retrieve, search, or view existing entries as a list(ListView) or retrieve a particular entry in detail (DetailView)
- UpdateView :update or edit existing entries in a table in the database.
- DeleteView :delete, deactivate, or remove existing entries in a table in the database.
- FormView :render a form to template and handle data entered by user.
Here i will give you simple example of django crud operations crud operation using class-based views, So let's see the below example:
Step 1 : Create a ProjectIn this second step, we’ll create a new django project using the django-admin. Head back to your command-line interface and run the following command:
django-admin startproject crudexampleStep 2 : Create a App
python3 manage.py startapp post
Next, you need to add it in the settings.py file as follows:
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'post', 'crispy_forms', ]Step 3 : Database Setup
Next step, we will modify the settings.py file and update the database settings to configure the mydb database:
settings.pyDATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'example', 'USER':'root', 'PASSWORD':'root', 'HOST':'localhost', 'PORT':'3306' } }Step 4 : Create a Model
In this step. we will require the database model for storing contacts.Open the post/models.py file and add the following code:
post/models.pyfrom django.db import models # Create your models here. class PostModel(models.Model): # fields of the model title = models.CharField(max_length = 200) description = models.TextField() # renames the instances of the model # with their title name def __str__(self): return self.title
After creating these model, you need to create migrations using the following command:
Step 5 : Create a Migrationspython manage.py makemigrations
After successfully run the above command go to the post/migrations/0001_initial.py
post/migrations/0001_initial.py# Generated by Django 4.0.5 on 2022-06-25 12:02 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='PostModel', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=200)), ('description', models.TextField()), ], ), ]
Next, you need to migrate your database using the following command:
python manage.py migrateStep 6 : Create a FormClass
Now in this step we will create a Django ModelForm for this model. Create form from Models. create a file forms.py:
post/forms.pyfrom django import forms from .models import PostModel # creating a django form class PostForm(forms.ModelForm): class Meta: model = PostModel fields = { 'title', 'description' }Step 7 : Creating the Views
In this step, we need to create the views for performing the CRUD operations.Open the post/views.py file and add:
post/views.pyfrom django.shortcuts import render from django.views import View from django.http import HttpResponse from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.views.generic.list import ListView from django.views.generic.detail import DetailView from .models import PostModel from django import forms from post.forms import PostForm # Create your views here. class PostCreate(CreateView): model = PostModel fields = [ 'title', 'description' ] success_url = '/' class PostList(ListView): # specify the model for list view model = PostModel class PostDetails(DetailView): # specify the model to use model = PostModel class PostUpdateView(UpdateView): # specify the model you want to use model = PostModel # specify the fields fields = [ "title", "description" ] # can specify success url # url to redirect after successfully # updating details success_url ="/" class PostDeleteView(DeleteView): # specify the model you want to use model = PostModel # can specify success url # url to redirect after successfully # deleting object success_url ="/"Step 8 : Creating Django Templates
Next will tell django to look for the templates in the templates folder.Next, inside the post folder create a templates folder:
Next, inside the templates folder, create the following files:
/templates/post/postmodel_list.html<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Django CRUD</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"> </head> <body> <div class="container mt-5 pt-5"> <div class="row d-flex justify-content-center"> <div class="col-md-12"> <div class="card"> <div class="card-header"> <div class="row"> <div class="col-md-9"> <h3>Django CRUD Operation Using Class-Based Views</h3> </div> <div class="col-md-3 text-right"> <a href="{% url 'create' %}" class="btn btn-success btn-sm">Create</a> </div> </div> </div> <div class="card-body"> <table class="table table-bordered"> <thead> <tr> <th width="350">Title</th> <th>Description</th> <th width="200">Action</th> </tr> </thead> <tbody> {% for object in object_list %} <tr> <td>{{ object.title }}</td> <td>{{ object.description }}</td> <td> <a href="{{ object.id }}/" class="btn btn-info btn-sm">Show</a> <a href="{{ object.id }}/update" class="btn btn-primary btn-sm">Edit</a> <a href="{{ object.id }}/delete" class="btn btn-danger btn-sm">Delete</a> </td> </tr> {% empty %} <tr> <td colspan="3">There are no record found.</td> </tr> {% endfor %} </tbody> </table> </div> </div> </div> </div> </div> </body> </html>
Next, open the /templates/post/postmodel_form.html file and the add:
/templates/post/postmodel_form.html{% load crispy_forms_tags %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Profile Image</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"> </head> <body> <div class="container mt-5"> <div class="row d-flex justify-content-center"> <div class="col-md-8"> <div class="card"> <div class="card-header"> <h4>Django CRUD Operation Using Class-Based Views</h4> </div> <div class="card-body"> <form method = "post" enctype="multipart/form-data"> {% csrf_token %} {{ form|crispy }} <button type="submit" class="btn btn-success">Submit</button> <a href="{% url 'home' %}" class="btn btn-secondary">Cancel</a> </form> </div> </div> </div> </div> </div> </body> </html>
Next, open the /templates/post/postmodel_detail.html file and the add:
/templates/post/postmodel_detail.html<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Post Details</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"> </head> <body> <div class="container mt-5 pt-5"> <div class="row d-flex justify-content-center"> <div class="col-md-12"> <div class="card"> <div class="card-header"> <div class="row"> <div class="col-md-9"> <h3>Post Details</h3> </div> <div class="col-md-3 text-right"> <a href="{% url 'home' %}" class="btn btn-success btn-sm">Back</a> </div> </div> </div> <div class="card-body"> <table class="table table-bordered"> <tbody> <tr> <th>{{ object.title }}</th> </tr> <tr> <td>{{ object.description }}</td> </tr> </tbody> </table> </div> </div> </div> </div> </div> </body> </html>
Next, open the /templates/post/postmodel_detail.html file and the add:
/templates/post/postmodel_detail.html{% load crispy_forms_tags %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Delete Record</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"> </head> <body> <div class="container mt-5 pt-5"> <div class="row d-flex justify-content-center"> <div class="col-md-12 text-center"> <form method="post">{% csrf_token %} <p>Are you sure you want to delete "<strong>{{ object }}</strong>"?</p> <button type="submit" class="btn btn-danger">Delete</button> </form> </div> </div> </div> </body> </html>Step 9 : Creating URLs
In this section, we’ll create the urls to access our CRUD views.Go to the urls.py post/urls.py file and update it as follows:
post/urls.pyfrom django.urls import path from . import views from .views import PostCreate, PostList, PostDetails, PostUpdateView, PostDeleteView urlpatterns = [ path('create', PostCreate.as_view(), name='create'), path('', PostList.as_view(),name='home'), path('<pk>/', PostDetails.as_view()), path('<pk>/update', PostUpdateView.as_view(),name='update'), path('<pk>/delete', PostDeleteView.as_view()), ]
Next, we will require the modify the urls.py your root preoject folder lets update the file.
crudexample/urls.pyfrom django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('post.urls')), ]Step 10 : Run the Server
In this step, we’ll run the local development server for playing with our app without deploying it to the web.
python manage.py runserver
Next, go to the http://localhost:8000/ address with a web browser.
I Hope It will help you....