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)
相关推荐
诚信爱国敬业友善几秒前
GUI编程(window系统→Linux系统)
linux·python·gui
查理零世17 分钟前
【蓝桥杯集训·每日一题2025】 AcWing 6134. 哞叫时间II python
python·算法·蓝桥杯
customer0823 分钟前
【开源免费】基于SpringBoot+Vue.JS个人博客系统(JAVA毕业设计)
java·vue.js·spring boot·后端·开源
紫雾凌寒26 分钟前
解锁机器学习核心算法|神经网络:AI 领域的 “超级引擎”
人工智能·python·神经网络·算法·机器学习·卷积神经网络
qq_4592384927 分钟前
SpringBoot整合Redis和Redision锁
spring boot·redis·后端
灰色人生qwer31 分钟前
SpringBoot 项目配置日志输出
java·spring boot·后端
sun lover39 分钟前
conda简单命令
python·conda
阿华的代码王国1 小时前
【从0做项目】Java搜索引擎(6)& 正则表达式鲨疯了&优化正文解析
java·后端·搜索引擎·正则表达式·java项目·从0到1做项目
EQUINOX11 小时前
lab4 CSAPP:Cachelab
java·后端·spring
Mike_188702783511 小时前
1688代采下单API接口使用指南:实现商品采集与自动化下单
前端·python·自动化