Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Adding a DeleteView in Django
A DeleteView is a Django generic view that provides an easy way to delete model instances from your application. It handles the deletion logic and provides confirmation functionality, similar to Django's admin interface.
Setting Up the Project
First, create a Django project and app. Add your app to settings.py ?
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'modelFormsDemo', # Your app name
]
URL Configuration
In your project's urls.py ?
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('modelFormsDemo.urls'))
]
In your app's urls.py ?
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name="home"),
path('student/delete/<int:pk>/', views.StudentDeleteView.as_view(), name="delete"),
path('success/', views.success, name='success')
]
Creating the Model
In models.py, define your Student model ?
from django.db import models
class Student(models.Model):
name = models.CharField(max_length=100)
standard = models.CharField(max_length=100)
section = models.CharField(max_length=100)
def __str__(self):
return f"{self.name} - {self.standard} ({self.section})"
Creating Forms
Create forms.py in your app directory ?
from django import forms
from .models import Student
class StudentForm(forms.ModelForm):
class Meta:
model = Student
fields = ['name', 'standard', 'section']
Implementing Views
In views.py, create your views including the DeleteView ?
from django.shortcuts import render
from django.views.generic.edit import DeleteView
from django.urls import reverse_lazy
from .models import Student
from .forms import StudentForm
def home(request):
if request.method == 'POST':
form = StudentForm(request.POST)
if form.is_valid():
form.save()
return render(request, 'success.html')
form = StudentForm()
students = Student.objects.all()
return render(request, 'home.html', {
'stu_form': form,
'students': students
})
class StudentDeleteView(DeleteView):
model = Student
template_name = 'delete_view.html'
success_url = reverse_lazy('success')
def success(request):
return render(request, 'success.html')
Creating Templates
Create a templates folder and add the following HTML files ?
home.html
<!DOCTYPE html>
<html>
<head>
<title>Student Management</title>
</head>
<body>
<h2>Add Student</h2>
<form method="post">
{% csrf_token %}
{{ stu_form.as_p }}
<button type="submit">Add Student</button>
</form>
<h2>Existing Students</h2>
{% for student in students %}
<p>{{ student.name }} - {{ student.standard }} ({{ student.section }})
<a href="{% url 'delete' student.pk %}">Delete</a></p>
{% empty %}
<p>No students added yet.</p>
{% endfor %}
</body>
</html>
delete_view.html
<!DOCTYPE html>
<html>
<head>
<title>Delete Student</title>
</head>
<body>
<h2>Delete Confirmation</h2>
<form method="post">
{% csrf_token %}
<p>Are you sure you want to delete "{{ object }}"?</p>
<input type="submit" value="Confirm Delete">
<a href="{% url 'home' %}">Cancel</a>
</form>
</body>
</html>
success.html
<!DOCTYPE html>
<html>
<head>
<title>Success</title>
</head>
<body>
<h2>Operation Successful!</h2>
<p>The operation was completed successfully.</p>
<a href="{% url 'home' %}">Back to Home</a>
</body>
</html>
Key Features of DeleteView
- model: Specifies which model to delete from
- template_name: The template for confirmation page
- success_url: Where to redirect after successful deletion
- context_object_name: Custom name for the object in template (optional)
Migration and Testing
Run migrations to create the database tables ?
python manage.py makemigrations python manage.py migrate python manage.py runserver
Conclusion
Django's DeleteView provides a secure and easy way to implement deletion functionality with built-in confirmation. It automatically handles the POST request for deletion and redirects to a success page, making it perfect for CRUD operations in web applications.
