Open In App
Related Articles

Django project to create a Comments System

Improve Article
Save Article
Like Article

Commenting on a post is the most common feature a post have and implementing in Django is way more easy than in other frameworks. To implement this feature there are some number of steps which are to be followed but first lets start by creating a new project.

How to create Comment Feature in Django?

  • Open command prompt and run the following commands.

Start a new django project as:

django-admin startproject my_project

After executing this command you will see following files and folder that django creates for you. To see this folder you can make use of tree command on command prompt or open the folder in an ide, in my case I have used sublime text editor.

Create a new app as:

python startapp portfolio_app

Django automatically creates files so that you can focus on your task without bothering of other things like making a file and structuring them.

In this article we will make a post model to post a picture:

The post consist of following fields:

2.Caption or description
3.Date posted
4.Author of the image.

First, importing the required modules in

from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User

Now, continuing with module, append the following snippet.


class Post(models.Model):
    image = models.ImageField(
        default ="default_foo.png", upload_to ="post_picture")
    caption = models.TextField()
    date_posted = models.DateTimeField(default =
    author = models.ForeignKey(User, on_delete = models.CASCADE)
    def __str__(self):
        return f'{}\'s Post- {self.title}'
    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)
        img =
        if img.height > 400 or img.width > 400:
            output_size = (300, 300)

Name of the model is post model (it could be any of your choice). Let us understand the details of each filed used.

Image field: This field allows to store image in the database. The default value includes  a default image which I have named as default_foo.png.It is automatically saved when no picture is available or posted by the user. This Image is located in a folder named Media in your my_project directory.  If a user upload a picture, it is uploaded in the directory named post_picture, set by the attribute upload_to.

Caption: This field depicts the description of the image named as caption for the image field.

Date posted: This field takes account of the time and date the image is uploaded. Default value saves the time at which this post is created. The time/date is not changed if the post is updated later after the post.

Author: This attribute takes account of the user posted this post. It takes django user as the parameter to do so. The on_delete filed takes care for abnormalities which might happen to the post if a user gets deleted. Models, cascade field deletes all the user related post data simultaneously when a user gets deleted.

__str__ method: These methods are also known as magic methods in python. It takes self as its attributes. This method shows the title information to the django admin at the backend.

save method:This method is override to save the post with user customized values.If we want to save images of a particular size in our database, save method is used to do so. For this ypu have to import PIL in your module to read the image.Open the image by open method into a variable and store it in a particular output size in your database to avoid storage of large images in your database.

After successfully creating the post model run the following commands on the terminal the make and save the changes in database.

python makemigrations
python migrate

This will make the post table in your database. I’m using django default database. 

For visualizing your tables and database I recommend you to download DB Browser for sqlite which will provide you an interface to view, edit all your schemas.

After implementing your post model now it’s time to implement comment feature on your post.

  1. Make a form in module to get the data.
  2. Make a function to save or delete the comment in module.
  3. Get the comments from the html file.

Make a form to collect the content of comment in module. If You don’t have in your django app, then create one .

Django has inbuilt forms to create it and access it directly without writing a new one from scratch.


from django import forms
from .models import Comment
class CommentForm(forms.ModelForm):
    content = forms.CharField(label ="", widget = forms.Textarea(
    attrs ={
        'placeholder':'Comment here !',
    class Meta:
        model = Comment
        fields =['content']

Moving to the module, to process and save the data coming from html form the following code goes on. I am implementing the comment feature in post detail view, you can use it wherever you want to, the method would be same.


from .forms import CommentForm
def post_detailview(request, id):
  if request.method == 'POST':
    cf = CommentForm(request.POST or None)
    if cf.is_valid():
      content = request.POST.get('content')
      comment = Comment.objects.create(post = post, user = request.user, content = content)
      return redirect(post.get_absolute_url())
      cf = CommentForm()
    context ={
    return render(request, 'socio / post_detail.html', context)

Importing CommentForm from module,  make an object of commentform and check if it is valid. Django provides built-in feature to check the form credentials and format by is_valid method. 

Scraping the content of post  by get method and creating a new  comment by create method followed by Save method saves the data of object created while creating new post in the database.

The cf object is passed into the html by context dictionary to access all the comments in HTML.

Finally, for getting the data from html form, a form tag is used with method used as post, since we have to send the data to the server. The following snippet shows how the value is taken from the form in the html.


{% load crispy_forms_tags %}
  <form method="POST">
    {% csrf_token %}

Here, Csrf_token is used for the security purpose. Django handles the encryption of form through this token.

as_p method is used to show the form in paragraph manner for better visualization.

Output – 

Comment box

You can show all the comments through the for loop in HTML. Django provides new HTML language to access data and variables passed in the context in module which contains for loops, if-else conditions etc.

You can view this features in my social media site project in my github.

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 02 Nov, 2023
Like Article
Save Article
Similar Reads
Complete Tutorials