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

7 投票
4 回答
6573 浏览
提问于 2025-04-15 19:36

我正在使用django.contrib.comments.views.moderation模块中的delete()函数。工作人员可以删除任何评论,这没问题。不过,我还想让注册的非工作人员也能删除他们自己的评论,而不是其他人的评论。我该怎么做呢?

4 个回答

2

虽然这个问题有点晚了,但你难道不能在模板中用类似的方法做到吗?

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

这段代码使用了Django的评论网址:

url(r'^delete/(\d+)/$',  'moderation.delete',           name='comments-delete'),
3

我刚遇到这个问题。

如果你只是重新实现评论应用中删除视图的逻辑,那就会把你的实现和评论应用的特定版本绑在一起。举个例子,评论应用实际上在你标记某个内容为删除时还会处理一些信号,而你提供的版本并没有做到这一点。

幸运的是,评论应用提供了一个函数,可以在不考虑权限的情况下实现核心的删除逻辑。使用这个函数虽然会让你依赖于内部的细节,但它的工作方式非常明确,要么完全有效,要么完全无效,不会出现半有效的情况。你可以创建自己的视图,设计自己的安全模型,然后调用评论应用提供的函数(从django.contrib.comments.views.moderation导入perform_delete)。

代码大概是这样的:

@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

你的具体细节会根据你的使用场景而有所不同。

我尝试过几种不同的方式(你可以在这个评论的历史中看到),我认为这个方法在各方面都比这里提供的原始解决方案要好。

5

如果你想把评论标记为已删除,就像 django.contrib.comments.views.moderation.delete() 这个函数所做的那样:

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()

撰写回答