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)
相关推荐
java1234_小锋9 分钟前
[免费]SpringBoot+Vue勤工助学管理系统【论文+源码+SQL脚本】
spring boot·后端·mybatis·勤工助学
爱笑的眼睛1123 分钟前
超越 `cross_val_score`:深度解析Scikit-learn交叉验证API的架构、技巧与陷阱
java·人工智能·python·ai
smj2302_796826521 小时前
解决leetcode第3782题交替删除操作后最后剩下的整数
python·算法·leetcode
踏浪无痕1 小时前
从 Guava ListenableFuture 学习生产级并发调用实践
后端·面试·架构
❀͜͡傀儡师1 小时前
SpringBoot 扫码登录全流程:UUID 生成、状态轮询、授权回调详解
java·spring boot·后端
可观测性用观测云2 小时前
观测云在企业应用性能故障分析场景中的最佳实践
后端
一 乐2 小时前
酒店预约|基于springboot + vue酒店预约系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端
gCode Teacher 格码致知2 小时前
Python基础教学:Python 3中的字符串在解释运行时的内存编码表示-由Deepseek产生
python·内存编码
翔云 OCR API2 小时前
承兑汇票识别接口技术解析与应用实践
开发语言·人工智能·python·计算机视觉·ocr