Blog with Django (Codemy.com) - 33 Comment Section


we need to associate new Comment model with Post model

add ordering!


1. models.py

class Comment(models.Model):
    post = models.ForeignKey(Post, related_name="comments", on_delete=models.CASCADE)
    name = models.CharField(max_length=250)
    body = models.TextField()
    date_added = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return '%s - %s' % (self.post.title, self.name)
on_delete=models.CASCADEblog post gets deleted, comment gets automatically deleted.related_name="commemts"this allow us to reference Comment models as comments
    def __str__(self):
        return '%s - %s' % (self.post.title, self.name)
how it's shown in admin area
makemigrations, migrate

2. register at admin

from django.contrib import admin
from .models import Comment

admin.site.register(Comment)

3. add dummy data


at admin website, add a post.

4. templates


we can call comments through post model.
Even though model's name is 'Comment'(singular), we call it as 'comments'(plural) because we set related_name to 'comments' related_name="commemts"add_posts.html
<!--Comment-->
<hr>
<h2>Comment</h2>
{% if not post.comments.all %}
    No Comments yet...<a href="#">Add one

{% else %}
    {% for comment in post.comments.all %}
        <strong>{{ comment.name }} - {{ comment.date_added }}</strong> <br>
        <br>
        {{ comment.body }}
        <br>
        <hr>
    {% endfor %}
{% endif %}

Results

  • when there are comments
  • No comments