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 %}
相关推荐
其美杰布-富贵-李25 分钟前
Spring Boot 依赖注入说明文档
java·spring boot·python
梦想的初衷~1 小时前
植被遥感反演与数据同化算法体系教程:从PROSAIL前向模拟到作物估产
人工智能·python·机器学习·作物模型·遥感数据同化·prosail·植被参数反演
Vect__1 小时前
MySQL 数据类型和约束:从字段设计到表结构建模
数据库·mysql
LadenKiller1 小时前
近期AI协作写量化规则,要按阶段安排任务
人工智能·python
天天进步20151 小时前
Python全栈项目--基于深度学习的图像超分辨率系统
开发语言·python·深度学习
张人玉1 小时前
C# WinForms——工厂管理系统(C# WinForms)
数据库·sqlite·c#·winform
ellenwan20262 小时前
近期AI协作量化实现,先补规则清晰度和流程完整性
人工智能·python
卷无止境2 小时前
Python 类型注解与运行时反射:从原理到工程实践
后端·python
AC赳赳老秦2 小时前
招投标公开数据自动化采集实战:基于 OpenClaw 的定时抓取与业务关键词精准推送
运维·服务器·数据库·自动化·测试用例·deepseek·openclaw
酷可达拉斯2 小时前
Linux操作系统-shell编程(0)
linux·运维·服务器·python·云计算