Django .delete()不起作用

时间:2014-08-05 22:24:26

标签: python django

我在Django中制作一个简单的bbs。

目前,我正试图删除前端的帖子。

这是我在views.py

中的代码
@login_required
def delete_post(request, id):
    post_to_delete = get_object_or_404(Post, pk=id)

    if post_to_delete.owner_user != request.user:
        return HttpResponseForbidden()

    if request.method == 'POST':
        form = DeletePostForm(request.POST, instance=post_to_delete)
        if form.is_valid():
            post_to_delete.delete()

            return HttpResponseRedirect('/') 
    else:
        form = DeletePostForm(instance=post_to_delete)

    return render(request,'delete_post.html', {'form':form})

我相信我正在使用.delete()函数,当我点击我的删除按钮时,我被带到了delete_post.html,但是当我回去查看admin中的帖子列表时,帖子仍然存在..

1 个答案:

答案 0 :(得分:0)

好的,在向您解释您不需要表单来删除实例之后。让我给你一个没有使用表格的文章。

@login_required
def delete_post(request, id):
    post_to_delete = get_object_or_404(Post, pk=id)

    if post_to_delete.owner_user != request.user:
        return HttpResponseForbidden()

    if request.method == 'POST':   
        post_to_delete.delete()
        return render(request,'delete_post.html', {'deleted':True})

    return render(request,'delete_post.html', {'deleted':False})

您可以在模板中使用deleted var。