Django添加删除文章功能

在我写的项目里,称类似文章的文本为entry。我想要在entry编辑页面(edit_entry)上添加一个删除按钮,点击后这条entry会被删除。

添加视图

文件~/应用/views.py

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.http import Http404

from .models import Entry

-- snip --

# 删除entry
@login_required
def delete_entry(request, entry_id):
    """删除既有条目"""
    # 根据id获取需要删除的entry
    entry = Entry.objects.get(id=entry_id)
    # 只有该entry的拥有者可以将其删除
    check_entry_owner(request, entry)
    # 调用.delete()方法删除文章
    entry.delete()
    # 完成删除后返回entry列表
    return redirect('aoyu_blog_logs:topic', topic_id=entry.topic.id)

装饰器@login_required确保只有已登录用户才能删除entry。

调用的函数check_entry_owner()确保只有entry拥有者可以将其删除。代码如下:

1
2
3
4
5
6
7
8
from django.http import Http404

-- snip --

def check_entry_owner(request, entry):  
    """核实entry关联到的用户是否为当前用户"""  
    if entry.topic.owner != request.user:  
        raise Http404

添加URL模式

文件~/应用/urls.py

1
2
3
4
5
6
--snip--
urlpatterns = [
    --snip--
    # 用于删除条目的页面
    path('delete_entry/<int:entry_id>/', views.delete_entry, name='delete_entry'),
]

修改模板

文件~/应用/templates/应用/edit_entry.html

1
2
3
4
5
6
7
8
9
--snip--
<form action="{% url 'aoyu_blog_logs:delete_entry' entry.id %}">
    {% csrf_token %}

    {% buttons %}
    <button type="submit" class="btn btn-outline-danger">删除该Entry</button>
    {% endbuttons %}
</form>
--snip--

我没有使用a标签,而是使用了一个表单。由于使用了Bootstrap,我不需要再去调CSS。

可以改进的地方是,点击删除按钮后弹出一个“二次提示”信息。现在是点击按钮后entry直接就被删除了。