Reputation: 197
I'm building a comment system and I want to show the replies to comments made.
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)
The thing is that I don't really know how to send the replies related to the individual comment to the template. Currently, my view is:
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'),
})
It's working fine, I can see the thread and it's comments. But how should I proceed to be able to do something as below to also show the replies to each comment?
{% for Comment in comments %}
{{ Comment.body }}
{%for Reply in replies %}
{{Reply.body }}
{% endfor %}
{% endfor %}
I've tried some horribles workarounds, which didn't work. I know there are some packages that does this but since I'm still learning as I go, I think it's better for me to do it myself. Also, I realize this question has been asked before, but the replies didn't clarify my problem.
It seems I'm missing something basic here. Thank you.
Upvotes: 0
Views: 833
Reputation: 45575
"Backward" relationships are described in the docs:
{% for Reply in Comment.reply_set.all %}
{{ Reply.body }}
{% endfor %}
Upvotes: 3