【问题标题】:How to provide a delete button for django built in comments framework如何为 django 内置的评论框架提供删除按钮
【发布时间】:2012-02-05 00:14:13
【问题描述】:

我正在使用 django 评论框架。说它提供了很多功能,而且我在源文件中也可以看到有各种选项,但是文档有点差。

有两个问题

  1. 我想为发布的每条评论提供一个delete button,并且我不想将用户重定向到另一个页面。我只想通过确认消息删除评论。我没有找到任何文档告诉我如何在django comments framework 中做到这一点
  2. 如果有error while submitting the comment form,用户是redirected to the preview page(也可以处理错误),我不想要这个。我希望用户被重定向到同一页面,并出现相应的错误。我该怎么做呢。

感谢任何帮助或指导

【问题讨论】:

    标签: django django-apps django-comments


    【解决方案1】:

    Timmy 的视图代码片段仍然缺少一个导入语句并且没有返回响应。这是相同的代码,更新到现在外部的 django_cmets 应用程序(django 1.6+):

    from django.shortcuts import get_object_or_404
    import django.http as http
    from django_comments.views.moderation import perform_delete
    from django_comments.models import Comment
    
    def delete_own_comment(request, id):
        comment = get_object_or_404(Comment, id=id)
        if comment.user.id != request.user.id:
            raise Http404
        perform_delete(request, comment)
        return http.HttpResponseRedirect(comment.content_object.get_absolute_url())
    

    这将在没有任何消息的情况下重定向回原始页面(但可能会少一条评论)。

    为此视图注册一个 URL:

     url(r'^comments/delete_own/(?P<id>.*)/$', delete_own_comment, name='delete_own_comment'),
    

    然后直接修改cmets/list.html包含:

    {% if user.is_authenticated and comment.user == user %}
       <a href="{% url 'delete_own_comment' comment.id %}">--delete this comment--</a>
    {% endif %}
    

    【讨论】:

      【解决方案2】:

      cmets 已经有一个删除视图,但它是审核系统的一部分。您需要向所有用户授予 can_moderate 权限,这显然允许他们删除他们想要的任何评论(不仅仅是他们的评论)。您可以快速编写自己的视图来检查他们正在删除的评论是否属于他们:

      from django.shortcuts import get_object_or_404
      from django.contrib.comments.view.moderate import perform_delete
      def delete_own_comment(request, comment_id):
          comment = get_object_or_404(Comment, id=comment_id)
          if comment.user.id != request.user.id:
              raise Http404
          perform_delete(request, comment)
      

      在你的模板中

      {% for comment in ... %}
      {% if user.is_authenticated and comment.user == user %}
          {% url path.to.view.delete_comment comment_id=comment.id as delete_url %}
          <a href="{{ delete_url }}">delete your comment</a>
      {% endif %}
      {% endfor %}
      

      对于第二个问题,you can see that the redirection will always happen if there are errors(即使设置了 preview=False)。没有太多的解决方法。您可以创建自己的视图来包装 post_comment 视图(或者只编写自己的 post_comment 而无需重定向)

      【讨论】:

      • 非常感谢您的解决方案,但我不知道为什么但它不起作用。我完全按照你的概述做了,但它不起作用
      • 显然if not comment.user.id is request.user.id: 出现错误,当我将其更改为if comment.user != request.user: 时,它开始正常工作。非常感谢您的帮助
      • 我发现上面代码的某些部分现在已经过时了。人们可能会发现我的问题的答案很有帮助stackoverflow.com/questions/61618792/…
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-01-30
      • 1970-01-01
      • 2012-03-09
      • 1970-01-01
      • 2012-04-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多