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 %}
相关推荐
Gauss松鼠会8 分钟前
GaussDB应用场景全景解析:从金融核心到物联网的分布式数据库实践
数据库·分布式·物联网·金融·database·gaussdb
守城小轩36 分钟前
Chromium 136 编译指南 - Android 篇:开发工具安装(三)
android·数据库·redis
尽兴-41 分钟前
如何将多个.sql文件合并成一个:Windows和Linux/Mac详细指南
linux·数据库·windows·sql·macos
Deng94520131442 分钟前
基于Python的旅游数据可视化应用
python·numpy·pandas·旅游·数据可视化技术
2401_878624791 小时前
pytorch 自动微分
人工智能·pytorch·python·机器学习
胖达不服输1 小时前
「日拱一码」021 机器学习——特征工程
人工智能·python·机器学习·特征工程
小小不董1 小时前
深入理解oracle ADG和RAC
linux·服务器·数据库·oracle·dba
胚芽鞘6812 小时前
查询依赖冲突工具maven Helper
java·数据库·maven
screenCui2 小时前
macOS运行python程序遇libiomp5.dylib库冲突错误解决方案
开发语言·python·macos
小眼睛羊羊2 小时前
pyinstaller打包paddleocr
python