Python 在Django中显示对个人评论的回复
我正在建立一个评论系统,我想显示对评论的回复Python 在Django中显示对个人评论的回复,python,django,Python,Django,我正在建立一个评论系统,我想显示对评论的回复 Models: class Comment(models.Model): created = models.DateTimeField(auto_now_add=True) thread = models.ForeignKey(Thread) body = models.TextField(max_length=10000) slug = models.SlugField(max_length=40, unique=T
Models:
class Comment(models.Model):
created = models.DateTimeField(auto_now_add=True)
thread = models.ForeignKey(Thread)
body = models.TextField(max_length=10000)
slug = models.SlugField(max_length=40, unique=True)
class Reply(models.Model):
created = models.DateTimeField(auto_now_add=True)
post = models.ForeignKey(Post)
body = models.TextField(max_length=1000)
问题是,我真的不知道如何将与个人评论相关的回复发送到模板。目前,我的观点是:
Views
def view_thread(request, thread_slug):
thread = Thread.objects.get(slug=thread_slug)
comments = Comment.objects.filter(thread = thread)
if request.method == 'POST':
form = ResponderForm(request.POST)
if form.is_valid():
comment = Comment()
comment.body = form.cleaned_data['body']
comment.thread = thread
comment.save()
new_form = ResponderForm()
reply_form = ReplyForm()
return render(request, 'view_thread.html', {
'Thread': thread,
'form': new_form,
'replyform': reply_form,
'Comments': comments.order_by('-created'),
})
else:
form = ResponderForm()
thread = Thread.objects.get(slug=thread_slug)
reply_form = ReplyForm()
return render(request, 'view_thread.html', {
'Thread': thread,
'form': form,
'replyform': reply_form,
'Comments': comments.order_by('-created'),
})
它的工作很好,我可以看到线程和它的评论。但是,我应该如何继续做下面的事情来显示对每条评论的回复呢
{% for Comment in comments %}
{{ Comment.body }}
{%for Reply in replies %}
{{Reply.body }}
{% endfor %}
{% endfor %}
我试过一些可怕的变通办法,但都不起作用。我知道有一些软件包可以做到这一点,但由于我仍在不断学习,我认为我最好自己去做。此外,我意识到以前有人问过这个问题,但这些回答并没有澄清我的问题
看来我缺少了一些基本的东西。
谢谢。“向后”关系是:
哇…我觉得自己好笨。我试着这样做,但没有意识到我在循环中,所以我用“…in Comments.reply\u set.all”代替Comment.reply\u set.all。非常感谢。
{% for Reply in Comment.reply_set.all %}
{{ Reply.body }}
{% endfor %}