Django displaying related objects

I have models for ProjectNotes and for ProjectNotesComments. ProjectNotesComments have a foreign key that is the ProjectNotes id. I am able to save comments on notes. I can see them in the admin panel.

However I have not been able to figure out how to display the comments on the notes.

Here are the models:

class ProjectNotes(models.Model):
    title = models.CharField(max_length=200)
    body = tinymce_models.HTMLField()
    date = models.DateField(auto_now_add=True)
    project = models.ForeignKey(Project, default=0, blank=True, on_delete=models.CASCADE, related_name='notes')

    def __str__(self):
        return self.title

class ProjectNoteComments(models.Model):
    body = tinymce_models.HTMLField()
    date = models.DateField(auto_now_add=True)
    projectnote = models.ForeignKey(ProjectNotes, default=0, blank=True, on_delete=models.CASCADE, related_name='comments')

Here is the view:

class ProjectNotesDetailView(DetailView):
    model = ProjectNotes
    id = ProjectNotes.objects.only('id')
    template_name = 'company_accounts/project_note_detail.html'
    comments = ProjectNotes.comments

This is the template I am currently using to test getting the comments to display:


{% extends 'base.html' %}

{% block content %}
<div class="section-container container">
  <div class="project-entry">
    <h2>{{ projectnotes.title }}</h2>
    <p>{{ projectnotes.body | safe }}</p>
  </div>
  <div>
</div>
{% for comment in comments %}
        <div class="comments" style="padding: 10px;">
          <p class="font-weight-bold">
            {{ comment.body | linebreaks }}
            
        </div>
        {% endfor %}
  
  <h2><a href="{% url 'add_project_note_comment' projectnotes.pk %}">add note</a></h2>
{% endblock content %}

Solution 1:

I don't think this actually works: comments = ProjectNotes.comments. You would need to override the get_context_data method, and set comments on the context_data to accomplish what you are attempting to do there.

However, you don't need to do that at all, since you can get to the comments from the ProjectNotes object, and the ProjectNotes object is already in the context. Simply change your for loop to this:

{% for comment in projectnotes.comments %}