Django按照文章ID删除文章

重点是'文章的ID'作为参数,如何在各个部分传递。

1、在视图函数部分

python 复制代码
@login_required
def article_list(request):
    articles = ArticlePost.objects.filter(author=request.user)
    context = {'articles': articles, }
    return render(request, 'article/column/article_list.html', context)

2、在html部分,代表删除的图标,被点击时,调用javascript中的del_article函数,这个函数包含参数article.id。view函数渲染这个html文件时,传递了articles变量,article是遍历articles后获得的,要获得article的各个属性,使用'.'方法。

html 复制代码
{% for article in articles %}
    <tr id={{ article.id }}>
        <td>{{ forloop.counter }}</td>
        <td><a href="{{ article.get_absolute_url }}">{{ article.title }}</a></td>
        <td>{{ article.column }}</td>
        <td>
            <a name="edit" href="{% url 'article:redit_article' article.id %}">
                <span class="fas fa-pencil-alt"></span>
            </a>
            <a name="delete" href="javascript:" onclick="del_article(this, {{ article.id }})">
                <span class="fas fa-trash-alt" style="margin-left: 20px;"></span>
            </a>
        </td>
    </tr>
{% endfor %}

3、在javascript部分,articleId获得article.id的值,并将其提交给服务器

javascript 复制代码
    function del_article(element, articleId) {
        console.log("Delete icon clicked")
        if (confirm("Are you sure you want to delete this column?")) {
            console.log("Column to delete:", articleId);
            fetch(`/article/delete-article/`, {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': getCookie('csrftoken')  // Django 的 CSRF token
                },
                body: JSON.stringify({
                                article_id: articleId,
                                }) //发送到后台的是一个字典,
            }).then(response => {
                if (response.ok) {
                    // 删除成功
                    alert('文章删除成功');
                    // 删除成功后刷新页面
                    window.location.reload();
                } else {
                    // 删除失败
                    alert('删除失败,请重试');
                }
            }).catch(error => {
                console.error('Error:', error);
                alert('删除失败,请重试');
            });
        }
    }

4、在视图部分,使用字典的键article_id,获得传递的'文章ID',并执行删除操作。

python 复制代码
@csrf_exempt
@login_required
def delete_article(request):
    if request.method == 'DELETE':
        try:
            data = json.loads(request.body)
            article_id = data.get('article_id')

            delete_article = ArticlePost.objects.get(id=article_id)
            delete_article.delete()
            return JsonResponse({'status': 'success'})
        except ArticlePost.DoesNotExist:
            return JsonResponse({'status': 'error', 'message': 'ArticleColumn not found'}, status=404)
        except Exception as e:
            return JsonResponse({'status': 'error', 'message': str(e)}, status=500)
    return JsonResponse({'status': 'error', 'message': 'Invalid request method'}, status=400)
相关推荐
狐凄15 分钟前
Python实例题:基于 Python 的简单聊天机器人
开发语言·python
悦悦子a啊1 小时前
Python之--基本知识
开发语言·前端·python
Piper蛋窝2 小时前
深入 Go 语言垃圾回收:从原理到内建类型 Slice、Map 的陷阱以及为何需要 strings.Builder
后端·go
笑稀了的野生俊3 小时前
在服务器中下载 HuggingFace 模型:终极指南
linux·服务器·python·bash·gpu算力
Naiva3 小时前
【小技巧】Python+PyCharm IDE 配置解释器出错,环境配置不完整或不兼容。(小智AI、MCP、聚合数据、实时新闻查询、NBA赛事查询)
ide·python·pycharm
路来了4 小时前
Python小工具之PDF合并
开发语言·windows·python
蓝婷儿4 小时前
Python 机器学习核心入门与实战进阶 Day 3 - 决策树 & 随机森林模型实战
人工智能·python·机器学习
六毛的毛4 小时前
Springboot开发常见注解一览
java·spring boot·后端
AntBlack4 小时前
拖了五个月 ,不当韭菜体验版算是正式发布了
前端·后端·python
小石潭记丶4 小时前
Django服务开发镜像构建
django·sqlite·pip