Python 从0开始 一步步基于Django创建项目(9)删除条目

本文实现的功能:

在城市列表页面,每个城市名称后,添加删除链接。

点击删除后,跳转至确认删除页面,执行删除或取消。

城市删除成功后,不在出现在城市列表页面,同时通过级联删除的方式,删除了与该城市关联的所有条目信息。

1、修改C:\D\Python\Python310\study\snap_gram\city_infos\templates\city_infos路径下的cities.html文件,添加删除链接。

html 复制代码
{% for city in cities %}
    <li>
        <a href="{% url 'city_infos:city' city.id %}">{{ city }}</a>----
        <a href="{% url 'city_infos:delete_city' city.id %}">删除</a>
    </li>

2、修改C:\D\Python\Python310\study\snap_gram\city_infos路径下的urls.py文件,添加上一步中使用的url

python 复制代码
#删除城市
path('delete_city/<int:city_id>/',views.delete_city,name='delete_city'),

3、修改C:\D\Python\Python310\study\snap_gram\city_infos路径下的views.py文件,添加对应上述url的视图函数

python 复制代码
#删除城市
def delete_city(request,city_id):
    city = City.objects.get(id=city_id)

    if request.method == 'POST':
        city.delete()  # 删除城市条目
        return redirect('city_infos:cities')  # 删除成功后重定向到城市列表页面
    # 如果请求方法不是 POST,渲染一个确认删除的页面供用户确认
    return render(request, 'city_infos/delete_city.html', {'city': city})

4、新建C:\D\Python\Python310\study\snap_gram\city_infos\templates\city_infos路径下的delete_city.html

html 复制代码
{% extends "city_infos/base.html" %}

{% block content %}
    <h1>确认:</h1>
    <p>确认删除城市:{{ city.name }}?</p>
    <form method='post'>
        {% csrf_token %}
        <button name="submit">删除</button>
    </form>
    <a href="{% url 'city_infos:cities' %}">取消</a>

{% endblock content %}
相关推荐
ylfhpy18 分钟前
Java面试黄金宝典30
java·数据库·算法·面试·职场和发展
Y1nhl21 分钟前
Pyspark学习一:概述
数据库·人工智能·深度学习·学习·spark·pyspark·大数据技术
维度攻城狮2 小时前
实现在Unity3D中仿真汽车,而且还能使用ros2控制
python·unity·docker·汽车·ros2·rviz2
简简单单做算法2 小时前
基于mediapipe深度学习和限定半径最近邻分类树算法的人体摔倒检测系统python源码
人工智能·python·深度学习·算法·分类·mediapipe·限定半径最近邻分类树
hvinsion3 小时前
基于PyQt5的自动化任务管理软件:高效、智能的任务调度与执行管理
开发语言·python·自动化·自动化任务管理
飞飞翼5 小时前
python-flask
后端·python·flask
林九生6 小时前
【Python】Browser-Use:让 AI 替你掌控浏览器,开启智能自动化新时代!
人工智能·python·自动化
猿界零零七6 小时前
执行paddle.to_tensor得到全为0
python·paddle
我有医保我先冲7 小时前
SQL复杂查询与性能优化:医药行业ERP系统实战指南
数据库·sql·性能优化
青花瓷7 小时前
智谱大模型(ChatGLM3)PyCharm的调试指南
人工智能·python·大模型·智谱大模型