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 %}
相关推荐
waterHBO1 小时前
python 爬虫 selenium 笔记
爬虫·python·selenium
kejijianwen2 小时前
JdbcTemplate常用方法一览AG网页参数绑定与数据寻址实操
服务器·数据库·oracle
编程零零七2 小时前
Python数据分析工具(三):pymssql的用法
开发语言·前端·数据库·python·oracle·数据分析·pymssql
AIAdvocate4 小时前
Pandas_数据结构详解
数据结构·python·pandas
小言从不摸鱼4 小时前
【AI大模型】ChatGPT模型原理介绍(下)
人工智能·python·深度学习·机器学习·自然语言处理·chatgpt
高兴就好(石5 小时前
DB-GPT部署和试用
数据库·gpt
这孩子叫逆6 小时前
6. 什么是MySQL的事务?如何在Java中使用Connection接口管理事务?
数据库·mysql
Karoku0666 小时前
【网站架构部署与优化】web服务与http协议
linux·运维·服务器·数据库·http·架构
码农郁郁久居人下6 小时前
Redis的配置与优化
数据库·redis·缓存
FreakStudio6 小时前
全网最适合入门的面向对象编程教程:50 Python函数方法与接口-接口和抽象基类
python·嵌入式·面向对象·电子diy