Creating a comment system
We will continue extending our blog application with a comment system that will allow users to comment on posts. To build the comment system, we will need the following:
- A comment model to store user comments on posts
- A Django form that allows users to submit comments and manages the data validation
- A view that processes the form and saves a new comment to the database
- A list of comments and the HTML form to add a new comment that can be included in the post detail template
Creating a model for comments
Let’s start by building a model to store user comments on posts.
Open the models.py
file of your blog
application and add the following code:
class Comment(models.Model):
post = models.ForeignKey(
Post,
on_delete=models.CASCADE,
related_name='comments'
)
name = models.CharField(max_length=80)
email = models.EmailField()
body = models.TextField()
...