如何在Django中对评论进行嵌套回复?

时间:2019-06-14 10:27:15

标签: python django

这是我当前在Django中使用评论应用程序的最终结果:

enter image description here

如何使父注释的子项彼此嵌套。

这些是关联的代码,如果您想对其进行一些更改:

models.py

class Comment(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    timestamp = models.DateTimeField(auto_now_add=True)
    content = models.TextField()
    parent = models.ForeignKey('self', null=True, blank=True, on_delete=models.CASCADE)
    # content types framework
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')    


    def children(self):
        return Comment.objects.filter(parent=self)

views.py

def blog_detail(request, blog_slug):
    blog = get_object_or_404(Blog, slug=blog_slug)
    session_key = 'blog_views_{}'.format(blog.slug)
    if not request.session.get(session_key):
        blog.blog_views += 1
        blog.save()
        request.session[session_key] = True

    content_type = ContentType.objects.get_for_model(Blog)
    object_id = blog.id
    # look at CommentManager as well
    comments = Comment.objects.filter(content_type=content_type, object_id=object_id).filter(parent=None)


    initial_data = {
        'content_type':blog.get_content_type,
        'object_id': blog.id
    }

    form = CommentForm(request.POST or None, initial=initial_data)

    if form.is_valid():
        c_t = form.cleaned_data.get('content_type')
        content_type = ContentType.objects.get(model = c_t)
        obj_id = form.cleaned_data.get('object_id')
        content = form.cleaned_data.get('content')
        parent_obj = None

        try:
            parent_id = int(request.POST.get('parent_id'))
        except:
            parent_id = None

        if parent_id:
            parent_qs = Comment.objects.filter(id=parent_id)
            if parent_qs.exists() and parent_qs.count() == 1:
                parent_obj = parent_qs.first()

        new_comment = Comment.objects.create(
            user = request.user, 
            content_type = content_type,
            object_id = obj_id,
            content = content,
            parent=parent_obj,
        )   

        return HttpResponseRedirect(new_comment.content_object.get_absolute_url())

    context = {
        'blog': blog,
        'categories': get_category_count(),
        'comments':comments,
        'form':form,
    }

    return render(request, 'blogs/blog-detail.html', context)

和html页面

{% for i in comments %}
    <div style="border-left: 4px solid #ccc;background-color: #f3f3f3; padding: 7px;">
        {{ i.content }} <br>
       <small class="text-secondary">
           <i class="fa fa-user"></i> {{ i.user|title }} | <i class="fa fa-clock"></i>  {{ i.timestamp|timesince }} ago |
           {% if i.children.count >= 0 %} {{ i.children.count }} comment(s) {% endif %} |<a href="#" class="reply-btn">reply</a>
        </small>

        <div class="replies" style="display:none !important;">
            {% for child in i.children %}
            <div style="border-left: 4px solid #ccc;background-color: #f3f3f3; padding: 7px;">
                    {{ child.content }} <br>
                    <small class="text-secondary">
                        <i class="fa fa-user"></i> {{ child.user|title }} | <i class="fa fa-clock"></i>  {{ child.timestamp|timesince }} ago
                    </small>
            </div>
            {% endfor %}

            <form method="POST">
                {% csrf_token %}
                {{ form|crispy }}
                <input type="hidden" value="{{ i.id }}" name="parent_id">
                <input type="submit" value="Submit" class="btn btn-success">
            </form>
        </div>

    </div>
    <hr>
{% endfor %}

非常感谢您帮助我如何为父评论添加嵌套回复,

编辑:您是否推荐其他解决方案?有任何第三方图书馆可以帮助我吗?

1 个答案:

答案 0 :(得分:1)

也许this可以帮助您!

功能

线程支持,因此注释可以嵌套。

针对所有模型或基于每个应用模型的可自定义最大线程级别。

有关通过电子邮件的后续评论的可选通知。

忽略链接以允许取消后续通知。

用户未通过身份验证时通过电子邮件发表评论确认。