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)
相关推荐
涡能增压发动积1 分钟前
windows 系统安装 python 的最好方式也许就是不安装
后端
f***68608 分钟前
Spring Boot 热部署
java·spring boot·后端
5***262210 分钟前
Spring Boot实现定时任务
java·spring boot·后端
Y***985110 分钟前
SpringBoot整合Email 邮件发送详解
java·spring boot·后端
i***118611 分钟前
SpringBoot中使用TraceId进行日志追踪
spring boot·后端·状态模式
kali-Myon13 分钟前
NewStarCTF2025-Week5-Web
java·python·安全·web安全·php·web·ctf
ziwu17 分钟前
【动物识别系统】Python+TensorFlow+Django+人工智能+深度学习+卷积神经网络算法
后端·深度学习·图像识别
DFT计算杂谈18 分钟前
Abinit-10.4.7安装教程
linux·数据库·python·算法·matlab
该用户已不存在19 分钟前
免费 SSL 证书缩短至 90 天,你的运维成本还能hold住吗
前端·后端·https
00后程序员19 分钟前
怎么在 iOS 上架 App,从构建端到审核端的全流程协作解析
后端