Create Comment Form with Django

We made comment section for post detail pages in the previous post. We are going to create comment form for this section, and we are going to able to post comment from the post page.

I will create a new file called comment_form.html in templates folder and I edited to comment.html like in the below:

<div class="comment-area">
    <div class="comment-header">
        <h5 class="comment-main-title">Comments</h5>
    </div>
    <div class="comment-content">
        {% for comment in comments %}
            <div class="media border p-3 comment-box">
                <!-- <img src="img_avatar3.png" alt="{{ comment.username }}" class="mr-3 mt-3 rounded-circle comment-image-of-user" style="width:60px;"> -->
                <div class="media-body comment-text">
                <h6 class="comment-username"> {{ comment.username }} <small class="comment-date"><i>Posted {{ comment.pub_date }}</i></small></h6>
                <p>{{ comment.content }}</p>      
                </div>
                <div class="clear"></div>
            </div>
        {% endfor %}
        </ul>
    </div>
    <div class="comment-form">
        {% include 'comment_form.html' %}
    </div>
</div>
Now, let's start to type comment form in the comment_form.html:
<form action="{% url 'comment' pk=post.pk %}" method="post">
{% csrf_token %}
<fieldset>
    <legend><h6>Post a comment</h6></legend>
    <label for="usr">username:</label>
    <input type="text" class="form-control" id="usr" name="comment-username">
    <label for="usr">Type your comment:</label>
    <textarea class="form-control" rows="5" id="comment" name="comment-textarea"></textarea>
</fieldset>
<input type="submit" value="Send Comment">
</form>
{% csrf_token %} is about security to avoid CSRF attacks. I'm not familiar with that but we should type this after start of form tag with post action.

Look at the action, I gave a url with post primary key. This primary key is actually a parameter which will be sent to the view function. 'comment' statement is name of url which will defined in urlspatterns list in the application folder will points the view function to activate. Also, there is a post method, this is http request method. If we want to give datas from the form, this operation will happen with post http request method. I added input which will be contain author's name of the comment, and textarea added for comment content which can be typed. These input and textarea tag must contain name parameter for getting data with post method from the view function. Lastly, the last button will triggered to the action and the request will be executed. 

Let's type the view called comment in the views.py:
from django.db.models.fields import TimeField
from django.http.response import HttpResponseRedirect
from django.shortcuts import render, get_object_or_404
from django.urls import reverse

from .models import Post, Comment

...

def comment(request, pk):
    post = get_object_or_404(Post, pk=pk)
    new_comment = Comment(
        username=request.POST.get('comment-username'), 
        content=request.POST.get('comment-textarea'),
        post = post
    )
    new_comment.save()
    return HttpResponseRedirect(reverse('detail', args=(str(post.pk))))
I created a new comment object and post request provides necessary data from the comment form and also post as foreign key.  After that, the object will saved with save method in the database. The page will be redirect to the same page. I used reverse function. This function takes the other view name and also its arguments.

Finally, we will add this view to the urls.py in the application folder:
urlpatterns = [
    path('', index, name="index"),
    path('about', about, name="about"),
    path('post/<int:pk>/', detail, name="detail"),
    path('post/<int:pk>/comment', comment, name="comment"),
]
So, let's try on the page:
Comment Form in Django
Finally, I could add a comment with comment form from the webpage. However, I'm not sure the things what I did is really secure and reliable. I said that because I'm a new learner of Django as server-side. We'll see what happen in the next. Good work! 

No comments:

Post a Comment