7

我正在使用 django.contrib.comments.views.moderation 模块中的 delete() 函数。允许工作人员删除任何评论帖子,这完全没问题。但是,我也想授予注册的编外人员删除他们自己的评论帖子的特权,并且只删除他们的自己的评论帖子。我怎样才能做到这一点?

4

4 回答 4

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()
于 2010-02-23T00:24:19.333 回答
3

我刚刚遇到了这个问题。

只需在评论应用的删除视图中重新实现逻辑,就会将您的实现与评论应用的特定版本结合起来。例如,当您将某些内容标记为已删除并且提供的版本不这样做时,评论应用程序实际也会处理信号。

幸运的是,评论应用程序提供了一个无需任何权限即可实现核心删除逻辑的功能。使用它会将你自己与内部细节联系起来,但它以一种非常具体的方式这样做,要么会崩溃,要么会工作,它永远不会成功。您可以使用自己的安全模型创建自己的视图,然后调用提供的评论应用功能(来自 django.contrib.comments.views.moderation import perform_delete)

代码看起来像这样:

@要求登录
def delete_my_comment(request, comment_id, next=None):
    评论 = get_object_or_404(comments.get_model(), pk=comment_id)
    如果comment.user == request.user:
        如果 request.method == "POST":
            perform_delete(请求,评论)
            返回重定向(“您的视图”,comment.content_object.id)
        别的:
            return render_to_response('comments/delete.html',
                                      {'comment':评论,“下一个”:下一个},
                                      请求上下文(请求))
    别的:
        提出Http404

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

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

于 2010-07-16T22:07:06.810 回答
2

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

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

这使用了 django 的评论 URL:

url(r'^delete/(\d+)/$',  'moderation.delete',           name='comments-delete'),
于 2010-03-20T08:03:35.700 回答
0

由于您if request.method == 'POST':在 HTML 中使用 , ,因此您需要通过表单发送它,如下所示:

<form action = "{% url 'comments-delete' %}" method = "POST">
    {% csrf_token %}
    <input type="hidden" name="comment_id" value="{{ comment.id }}"/>
    <input type="hidden" name="blogs_id" value="{{ blogs.id }}"/>
    <button>Delete</button>
</form>

视图.py

def delete_comment(request):
id = request.POST['comment_id']
pk = request.POST['blogs_id']
if request.method == 'POST':
    comment = get_object_or_404(Comment, id=id, pk=pk)
    try:
        comment.delete()
        messages.success(request, 'You have successfully deleted the comment')

    except:
        messages.warning(request, 'The comment could not be deleted.')

return redirect('get_posts')

网址.py

path('delete/comment/', delete_comment, name='delete_comment'),

(使用 Django 2)

于 2018-07-11T09:27:38.703 回答