锋哥原创的Python Web开发 Django5视频教程:
2024版 Django5 Python web开发 视频教程(无废话版) 玩命更新中~_哔哩哔哩_bilibili2024版 Django5 Python web开发 视频教程(无废话版) 玩命更新中~共计31条视频,包括:2024版 Django5 Python web开发 视频教程(无废话版) 玩命更新中~、第2讲 Django5安装、第3讲 Django5创建项目(用命令方式)等,UP主更多精彩视频,请关注UP账号。https://www.bilibili.com/video/BV14Z421z78C/视图类DeleteView的使用方法与视图类UpdateView类似,视图类DeleteView只能删除单条数据,路由变量为模型主键提供查询范围,因为模型主键具有唯一性,所以通过主键查询能精准到某条数据。查询出来的数据通过POST 请求实现数据删除。
views.py里面,我们新建Delete类,继承DeleteView
class Delete(DeleteView):
# 设置模版文件
template_name = 'student/delete.html'
# 设置模型外的数据
extra_context = {'title': '学生信息删除'}
# 设置上下文对象名称
context_object_name = 'student'
# 设置查询模型
model = StudentInfo
# 执行成功后跳转地址
success_url = '/student/list'
urls.py里加下映射:
path('student/delete/<int:pk>', helloWorld.views.Delete.as_view()),
student下新建delete.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{ title }}</title>
</head>
<body>
<h3>{{ title }}</h3>
<form method="post">
{% csrf_token %}
您确定更要删除 id:{{ student.id }} name:{{ student.name }} age:{{ student.age }} 的记录吗 ?
<input type="submit" value="确定">
</form>
</body>
</html>
list.hml加下 <a href="/student/delete/{{ student.id }}">删除</a>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{ title }}</title>
</head>
<body>
<h3>{{ title }}</h3>
<a href="/student/create">新增学生</a>
<table border="1">
<tr>
<th>编号</th>
<th>姓名</th>
<th>年龄</th>
<th>操作</th>
</tr>
{% for student in student_list %}
<tr>
<td>{{ student.id }}</td>
<td>{{ student.name }}</td>
<td>{{ student.age }}</td>
<td>
<a href="/student/{{ student.id }}">查看详情</a>
<a href="/student/update/{{ student.id }}">修改</a>
<a href="/student/delete/{{ student.id }}">删除</a>
</td>
</tr>
{% endfor %}
</table>
<br>
{% if is_paginated %}
{% if page_obj.has_previous %}
<a href="/student/list?page={{ page_obj.previous_page_number }}">上一页</a>
{% endif %}
{% for current in paginator.page_range %}
{% if current == page_obj.number %}
<a href="/student/list?page={{ current }}"><b><font color="blue">{{ current }}</font></b></a>
{% else %}
<a href="/student/list?page={{ current }}">{{ current }}</a>
{% endif %}
{% endfor %}
{% if page_obj.has_next %}
<a href="/student/list?page={{ page_obj.next_page_number }}">下一页</a>
{% endif %}
{% endif %}
</body>
</html>
运行测试:浏览器输入:http://127.0.0.1:8000/student/list
点击删除,进入删除确定页面:
点击 确定,django帮我删除数据后,转发到列表页面: