html – List One to Many Relationship-ThrowExceptions

Exception or error:

I’m sure this is a very basic question but I have a OneToMany Relationship and I wish to list all the associated children on a page. Here’s what i have so far.

Model File

from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse

class Post(models.Model):
    title = models.CharField(max_length=100)
    date_posted = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse ('blog-post' , kwargs = {'pk': self.pk})


class Paragraph(models.Model):
    content = models.TextField(default='')
    post = models.ForeignKey(Post,default='', on_delete=models.CASCADE)

    def __str__(self):
        return self.content

class Subtitle(models.Model):
    subtitle = models.CharField(max_length=100,default='')
    post = models.ForeignKey(Post,default='', on_delete=models.CASCADE)

    def __str__(self):
        return self.subtitle

View

    model = Post
    template_name = 'blog/post.html'
    context_object_name = 'post'

HTML FILE

  {%block content%}
  {% if post.author == user %}
  <a href="{%url 'blog-update' post.id %}">Edit</a>
  <a href="{%url 'blog-delete' post.id %}">Delete</a>
  {% endif %}
          <div class = 'content'>
              <h2>{{post.title}}</h2>
              <!-- I want to show Subtitle here--><p></p>
              <!-- I want to show Paragraph here--><p></p>
              <h3>By: {{post.author}} on {{post.date_posted}}</h3>
          </div>
  {% endblock content %}
How to solve:

Leave a Reply

Your email address will not be published. Required fields are marked *