您好,我有一个帖子博客,其中有一个带有帖子的主页,如果您单击它,您将被重定向到post_detail页面。现在,我希望用户允许删除他们所获得的评论,但我希望他们留在同一post_detail页面上。我无法克服,希望有人可以帮助我。预先感谢。
post_detail.html
<div class="container">
<br>
<h1 style="text-align:center;">{{post.post}} </h1>
<p style="font-size:small;text-align:center;">{{post.created_on}}</p>
<button type="button" class="btn btn-secondary float-right" data-toggle="modal" data-target="#exampleModal" data-whatever="@mdo">Yorum At</button>
<br>
<br>
<br>
{% for i in commentmodel_list%}
<h4 >{{i.comment}}</h4>
{% if i.author_security == user%}
<a style="float:right;color:red;"href="{% url 'forum:delete' slug=post.slug comment_id=i.id %}"><i class="fas fa-minus-circle"></i></a>
{% endif %}
{% if i.author is none %}
<p style="font-size:small;">Anonim | {{i.created_on}}</p>
{% else%}
<p style="font-size:small;"><a style="text-decoration:none;" href="#">@{{i.author}}</a> | {{i.created_on}}</p>
{% endif %}
<hr>
<br>
{% endfor %}
</div>
urls.py
app_name='forum'
urlpatterns=[
path('', views.PostList.as_view(), name='post'),
path('<slug:slug>/', views.PostDetail.as_view(), name='post_detail'),
path('delete/<slug:slug>/<comment_id>/',views.delete_post,name='delete')
]
views.py
def delete_post(request,slug=None,comment_id=None):
comment_delete=Comment.objects.get(id=comment_id)
comment_delete.delete()
post = Post.objects.get(slug=slug)
return redirect('forum:post_detail', slug= post)
答案 0 :(得分:0)
我强烈建议您通过提交POST request with CSRF token删除评论,否则容易出现CSRF attack。当您提交表单时,可以在其中添加一个输入,该输入的值表示当前页面,此后您将重定向到该页面。伪代码:
<form action="{% url 'forum:delete' slug=post.slug comment_id=i.id %}"
method="POST">
{% csrf_token %}
<input type="hidden" name="current_post" value="{{ post.slug }}">
<input type="submit>
</form>
视图:
def delete_post(request, comment_id=None):
Comment.objects.filter(id=comment_id).delete()
return redirect('forum:post_detail', slug= request.POST['current_post'])
如果通过“我希望他们留在同一post_detail页面上”表示您不想在浏览器中执行重定向,而是希望通过ajax删除它,这并不明显。如果是这种情况,请检查Django documentation about AJAX request with CSRF,因为有一个示例如何精确地做到这一点。