在 Django 中添加 DeleteView
DeleteView 是 Django 中的一个视图,用于从前端删除任何模型数据。它是一个内置视图,可以轻松应用。它在删除视图方面就像管理员页面一样。在实际项目中非常有用。
首先,创建一个 Django 项目和一个应用。我创建的项目名为 "tutorial11",应用名为 "modelFormsDemo"。
现在,让我们做一些基本的事情。在 settings.py 中添加应用 -
INSTALLED_APPS+ = ['modelFormsDemo']
在项目的 urls.py 中 -
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('modelFormsDemo.urls'))
]这里我们包含了应用的 url。
在应用的 urls.py 中 -
from django.urls import path,include
from . import views
urlpatterns = [
path('', views.home,name="home"),
path('student/delete//', views.StudentDeleteView.
as_view(),name="delete"),
path('success/',views.success,name='success')
]这里我们创建了 3 个 URL:一个用于渲染前端,DeleteView 用于删除,Success 用于删除后重定向。
示例
在 models.py 中,添加以下内容 -
from django.db import models # Create your models here. class Student(models.Model): name=models.CharField(max_length=100) standard=models.CharField(max_length=100) section=models.CharField(max_length=100)
这里我们创建了一个简单的模型。
在 views.py 中,添加以下内容 -
from django.shortcuts import render
from .forms import StudentForm
from django.views.generic.edit import DeleteView
from .models import Student
from django.urls import reverse_lazy
# Create your views here.
def home(request):
if request.method=='POST':
form=StudentForm(request.POST)
if form.is_valid():
form.save()
stuForm=StudentForm()
return render(request,'home.html',{"stu_form":stuForm})
class StudentDeleteView(DeleteView):
model=Student
template_name='delete_view.html'
success_url=reverse_lazy("success")这里,在 home 视图中,我们渲染了前端,在 DeleteView 中,我们渲染了 delete_view.html,它将提示确认删除。
在应用目录中创建 forms.py 并编写以下内容 -
from django import forms from .models import Student class StudentForm(forms.ModelForm): class Meta: model=Student fields=['name', 'standard', 'section']
这里我们创建了简单的表单,我们将在 home 视图中渲染它。
现在创建一个 templates 文件夹,并在其中添加三个文件 home.html、delete_view.html 和 success.html。
在 home.html 中 -
<!DOCTYPE html>
<html>
<head>
<title>TUT</title>
</head>
<body>
{% for fm in stu_form %}
<form method="post">
{%csrf_token%}
{{fm.errors}}<br>
{{fm.label}}:{{fm}}<br>
{%endfor%}
<button type="submit">Submit</button>
</form>
</body>
</html>在 delete_view.html 中 -
<!DOCTYPE html>
<html>
<head>
<title>TUT</title>
</head>
<body>
<form method="post">{% csrf_token %}
<p>Are you sure you want to delete "{{ object }}"?</p>
<input type="submit" value="Confirm">
</form>
</body>
</html>在 success.html 中 -
<!DOCTYPE html> <html> <head> <title>TUT</title> </head> <body> <h2>Success</h2> </body> </html>
所有这三个都是我们正在渲染的 HTML 文件。home.html 用于添加学生,delete_view.html 用于删除学生,success.html 用于重定向。
现在您可以继续检查输出。
输出
Home.html -

如果您访问 http://127.0.0.1:8000/student/delete/(学生对象ID)/,那么您将看到我们的 delete_view.html。
Delete_view.html -

数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP