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)
相关推荐
IT_陈寒6 分钟前
Java并行流把我坑惨了:原来不是线程安全的!
前端·人工智能·后端
染指111014 分钟前
76.高级RAG-后检索器(时间排序)
人工智能·python·llama_index·llamaindex
weixin_440784111 小时前
Java基础常见题
java·开发语言·python·java基础
Lihua奏1 小时前
跨域:浏览器到底拦住了什么
后端
跨境小彭2 小时前
Python列表去重的6种高效方法(含保留顺序+性能对比)
开发语言·python
今天AI了吗2 小时前
Python 基础语法从入门到使用详解
开发语言·人工智能·python
Lyra_Infra2 小时前
Docker OCI Runtime 启动失败问题排查与解决
后端·docker·架构
苏灿烤鱼2 小时前
从微信公众号内容到视频号视频:自动化视频生成的技术实现
人工智能·python·ffmpeg
XuCoder2 小时前
Redis 哨兵模式:它到底是怎么保证高可用的
后端
金銀銅鐵2 小时前
[Python] 借助 Pillow 和 NumPy 生成与斐波那契数列有关的图案
python·数学