允许用户在Djang中删除自己的评论

2024-05-15 18:20:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用的delete()函数来自django.contrib.comments.评论.观点.适度模块。工作人员可以删除任何评论帖子,这是完全可以的。不过,我也希望给予已登记的非工作人员删除他们自己的评论帖子的特权,而且只有他们自己。我怎样才能做到这一点?在


Tags: 模块django函数评论contribdeletecomments帖子
3条回答

{1>就像你想要删除的评论一样:

from django.contrib.auth.decorators import login_required
from django.contrib.comments.models import Comment
from django.shortcuts import get_object_or_404
from django.conf import settings
from django.contrib import comments

@login_required
def delete_own_comment(request, message_id):
    comment = get_object_or_404(comments.get_model(), pk=message_id,
            site__pk=settings.SITE_ID)
    if comment.user == request.user:
        comment.is_removed = True
        comment.save()

我刚碰到这个问题。在

只要在comments应用程序的delete视图中重新实现逻辑,就可以将您的实现与comments应用程序的特定版本相结合。例如,当你将某个内容标记为已删除,而提供的版本没有这样做时,comment应用程序实际也会处理信号。在

幸运的是,comments应用程序提供了一个不需要任何权限就可以实现核心删除逻辑的功能。使用它会将你自己与内部细节联系在一起,但它以一种非常具体的方式来实现,它要么会崩溃,要么会起作用,它永远不会半途而废。您可以使用自己的安全模型创建自己的视图,然后调用提供的注释应用程序函数(从django.contrib.comments.评论.观点.适度导入执行删除)

代码如下所示:

@login_required
def delete_my_comment(request, comment_id, next=None):
    comment = get_object_or_404(comments.get_model(), pk=comment_id)
    if comment.user == request.user:
        if request.method == "POST":
            perform_delete(request, comment)
            return redirect("your_view", comment.content_object.id)
        else:
            return render_to_response('comments/delete.html',
                                      {'comment': comment, "next": next},
                                      RequestContext(request))
    else:
        raise Http404

您的详细信息将根据您的用例而有所不同。在

我已经经历了一些变化(你可以在这个评论的历史中看到),我认为这个在所有方面都比这里提供的原始解决方案更好。在

虽然现在有点晚了,你不能在模板中做同样的事情吗?在

{% if user == comment.user %}
  <a href="{% url comments-delete comment.id %}">delete comment</a> 
{% endif %}

这将使用django的评论URL:

^{pr2}$

相关问题 更多 >