博客五部曲之二 - 高级博客


559 浏览 2 years, 11 months

21 删除确认视图

版权声明: 转载请注明出处 http://www.codingsoho.com/

本节将会完成评论的删除,在删除时会提示是否删除,如果确定删除,成功之后重定向到帖子位子

添加comment_delete函数,当POST提交是,删除帖子,并重定向到它的父节点去。

def comment_delete(request, id):
    obj = get_object_or_404(Comment, id=id)
    if request.method == "POST":
        parent_obj_url = obj.content_object.get_absolute_url()
        obj.delete()
        messages.success(request, "This has been deleted")
        return HttpResponseRedirect(parent_obj_url)
    context = {
        "object":obj,
    }
    return render(request, "confirm_delete.html", context)

记得添加这个函数的URL

urlpatterns = [
    url(r'^(?P<id>\d+)/delete$', comment_delete, name="delete"),   
]

创建新的confirm_delete.html模板,用于确认是否删除。

<div class="row">
    <div class="col-sm-6 col-sm-offset-3">
        <h1>Confirm Delete</h1>
        <form method="POST" action="">{% csrf_token %}
            <p>Are you sure you want to delete : "{{object.content}}"?</p>
            <input type="submit" value="confirm" class="btn btn-warning">
            <a href="{{object.get_absolute_url}}" class="btn btn-default">Cancel</a>        
        </form>
    </div>
</div>