评论未删除

时间:2019-03-13 15:04:46

标签: python django

我为博客创建了一个注释模型,我想为用户提供一种删除注释的方法,因此我为其创建了一个基于函数的视图,但是它没有用,所以我决定使用基于类的视图,但是两者的视图给出相同的错误。唯一发生的是,该网址之后会得到一个?,并且页面会按原样刷新。下面分别给出了基于函数的视图和基于类的视图

基于功能

def comment_delete(request, pk):
    comment_to_delete=get_object_or_404(comment,pk=pk)
    if request.method=='POST':
        post_url=comment_to_delete.content_object.get_absolute_url()
        comment_to_delete.delete()
        messages.success(request, 'Your comment has been deleted')
        return HttpResponseRedirect(post_url)

    context={
        'comment':comment_to_delete
    }
    return render(request, 'blog/confirm_delete.html', context)

基于类

class DeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView):
    model = comment
    success_url = '/'

    def test_func(self):
        comment= self.get_object()
        if self.request.user == comment.user:
            return True
        return False

确认页面的HTML

{% extends 'blog/base.html' %}
{% block content %}



<form>
    <p>are you sure you want to delete {{ comment }}</p>
    <input type="submit" value="confirm" >

</form>


{% endblock %}

models.py

class comment(models.Model):
    post=models.ForeignKey(Blog, on_delete=models.CASCADE)
    user=models.ForeignKey(User, on_delete=models.CASCADE)
    content=models.TextField(max_length=160)
    timestamp=models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return '{}-{}'.format(self.post.title,str(self.user.username))

    def get_absolute_url(self):
        return reverse('comment', kwargs={"pk": self.pk})

2 个答案:

答案 0 :(得分:1)

您需要在表单中添加发布请求。发布请求需要tokens才能免受Cross Site Request Forgeries的影响。通常,每次发布请求都会传递令牌。

<form method="POST">
    {% csrf_token %}
    <p>are you sure you want to delete {{ comment }}</p>
    <input type="submit" value="confirm" >
</form>

答案 1 :(得分:0)

问题出在您的模板中,而不是您的视图中。您需要将method="post"添加到表单中以进行POST请求,并添加{% csrf_token %}以防止CSRF错误。

<form method="post">
    {% csrf_token %}
    <p>are you sure you want to delete {{ comment }}</p>
    <input type="submit" value="confirm" >
</form>