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 %}
相关推荐
阿凡观察站3 分钟前
2026年工程项目管理软件推荐:这5款主流产品值得关注
大数据·数据库·低代码·finebi·简道云
逸Y 仙X26 分钟前
文章二十一:ElasticSearch 词项查询与调度查询实战
java·大数据·数据库·elasticsearch·搜索引擎
李李李勃谦34 分钟前
鸿蒙PCBI 报表工具:连接数据库与可视化报表生成
数据库·华为·交互·harmonyos
czlczl200209251 小时前
MAX()和MIN()优化
数据库·mysql·性能优化
开源情报局1 小时前
79%的企业在用AI Agent,但只有2%规模化落地——问题出在哪?
人工智能·python
算法与双吉汉堡2 小时前
【Nanobot项目笔记】项目架构
python·ai·agent·智能体
knight_9___2 小时前
LLM工具调用面试篇6
人工智能·python·面试·职场和发展·llm·agent
用户3962691060032 小时前
asyncio + subprocess:Python异步调用外部命令踩坑实录
python
消失的旧时光-19432 小时前
SQL 第一篇:CRUD 实战,从 user 表开始写接口
数据库·sql·mysql
AI砖家2 小时前
Claude Code Superpowers 安装使用指南:让 AI 编程从“业余”走向“工程化”
前端·人工智能·python·ai编程·代码规范