如何在django模板中显示评论及其回复?

时间:2017-09-16 08:55:43

标签: django django-models django-templates django-views django-orm

我想在模板中显示评论及其回复。但是有一个问题,每个回复都可能有其他一些回复。以下代码段是我的CommentCommentReply型号:

class Comment(models.Model):
    author = models.ForeignKey(Profile, related_name="c_sender", on_delete=models.CASCADE, unique=False)
    comment = models.CharField(max_length=500, unique=False)
    created_date = models.DateTimeField(auto_now_add=True)
    edited_date = models.DateTimeField(blank=True, null=True)

    def __str__(self):
        return self.comment

    @property
    def replys(self):
        return CommentReply.objects.filter(comment_id=self)


class CommentReply(models.Model):
    comment_id = models.ForeignKey(Comment, related_name='sender', on_delete=models.CASCADE)
    reply_id = models.ForeignKey(Comment, related_name='reply', on_delete=models.CASCADE)

更新 另外,我有一个WorksComments模型,每个与工作模型相关的注释都保存在那里。

 class WorkComment(models.Model):
     work_id = models.ForeignKey(Work, on_delete=models.CASCADE, related_name='e_exercise', unique=False)
     comment_id = models.ForeignKey(Comment, related_name='e_comment',  unique=False)

下面的代码片段是我的观点:

comments = WorkComment.objects.filter(work_id=work).all()
return render(request, 'work.html', {'comments': comments})

我的问题是如何在其下显示评论及其回复,并且每个回复都可能有其他回复,我也想要显示它们。

1 个答案:

答案 0 :(得分:0)

首先要把它放在你的书签中; https://ccbv.co.uk/

为了显示实例的详细信息,您可能会在此处想要Detail View

设置网址...

from django.conf.urls import url

from work.views import WorkDetailView

urlpatterns = [
    url(r'^(?P<id>[-\d]+)/$', WorkDetailView.as_view(), name='work-detail'),
]

观点;

from django.views.generic.detail import DetailView
from django.utils import timezone

from work.models import Work

class WorkDetailView(DetailView):

    model = Work

    def get_context_data(self, **kwargs):
        context = super(WorkDetailView, self).get_context_data(**kwargs)
        context['comments'] = WorkComment.objects.filter(work_id=self.object.id).all()
        return context

然后一个简单的视图可能是work/work_detail.html

<h1>{{ object.title }}</h1>
<p>{{ object.content }}</p>
<h2>Comments</h2>
{% for comment in comments %}
    {{ comment }}
{% endfor %}