Create a forum application using django #13: Make a comment system, Edit Comment and Protect user comments

in #utopian-io5 years ago

Repository

https://github.com/python

What Will I Learn?

  • Make a comment system
  • Edit Comment and Protect user comments from other users

Requirements

  • Basic Python
  • Install Python 3
  • Install Django

Resources

Difficulty

Basic

Tutorial Content

This tutorial is a continuation of the previous tutorial series, there are many things that we have made, for those of you who have just followed this tutorial, I suggest you look at other tutorials in the curriculum below. Just information we have added new features to our forum application. In this tutorial, I will deepen the comment system that is on our forum application, for that we just start this tutorial.

Make a comment system

In this section, we will make a comment system which is a continuation of the previous tutorial, here I will create a CommentCreateView function. This function will be used to save and connect forums with comments. So each forum can have many comments from many users. For more details, we can see in the example below:

forums/views.py

from .models import Comment

class CommentCreateView(CreateView):
    model = Comment
    fields = ['desc']

    def form_valid(self, form):
        _forum = get_object_or_404(Forum, id=self.kwargs['pk'])
        form.instance.user = self.request.user
        form.instance.forum = _forum
        return super().form_valid(form)
  • model = Comment: This function we will define the model to be used is Comment, this is the model that we have imported from .models import Comment.

  • fields = ['desc']: Define the field to be used, in this tutorial we will only use the desc field.

  • def form_valid(self, form): before we save the comment data we will first confirm whether the data is correct. to check it we can use form_valid (). In this function we will pass the self and forum values. We use self to access properties in this class. We will use the form so that we can access the form.

  • get_object_or_404(Forum, id=self.kwargs['pk']): We can fetch data with this function get_object_or_404(). The data we will fetch data in the Forum Forum module and the second parameter is the keyword argument id=self.kwargs['pk']. We need something unique when pulling data in the Forum. This second parameter is the primary key (id).

  • We will store data in the user model. For that, we need to access the model by creating an instance. To make instance a user model, we can do it like this form.instance.user and the data we store comes from self.request.user.

  • Here we will also store forum data. So we also have to instantiate it form.instance.forum and the data comes _forum.

ezgif.com-video-to-gif.gif

Edit Comment

Of course, when making comments, we don't want the comments to be absolute and cannot change. then from that, we will create a function that will be used to edit comments. As we learned in the previous tutorial we need to create a URL to edit comments. the following is the URL:

forums/urls.py

from django.urls import path
from .views import (ForumCreate, ForumListView, ForumUserListView, 
                   ForumDetailView, ForumUpdateView, ForumDeleteView, CommentCreateView, CommentUpdateView) // Define class view CommentUpdateView

urlpatterns = [
    path('', ForumListView.as_view(), name='forum-list'),
    path('add/', ForumCreate.as_view(), name='forum-add'),
    path('edit/<int:pk>', ForumUpdateView.as_view(), name='forum-edit'),
    path('delete/<int:pk>', ForumDeleteView.as_view(), name='forum-delete'),
    path('<slug:slug>/', ForumDetailView.as_view(), name='forum-detail'),
    path('by/<username>/', ForumUserListView.as_view(), name='forum-by'),
    path('add-comment/<int:pk>', CommentCreateView.as_view(), name='add-comment'),
    path('edit-comment/<int:pk>', CommentUpdateView.as_view(), name='edit-comment'), // URL edit
]
  • We create a new URL to edit comments 'edit-comment/<int: pk>, Because editing comments must be with a specific ID we will pass a unique parameter, that is the primary key <int: pk>.

  • And then we will define what class view we will use. At this URL we will use the CommentUpdateView class. to use it we must import it first like this from .views import CommentUpdateView. We add an alias from this URL to make it easier to use. The alias is name = 'edit-comment'.

We have finished in the URL, now we will create a CommentUpdateView class. We can make it in forums / views.py. For more details, we can see in the example below:

forums/views.py

@method_decorator(login_required, name='dispatch') // Protection if not log in
class CommentUpdateView(OwnerProtectMixin, UpdateView):
    model = Comment
    fields = ['desc']
    template_name = 'forums/forum_update_comment.html'
  • In this class we will use a mixin called OwnerProtectMixin. We have made this function in the previous tutorial. for more details, you can follow this tutorial. This function aims to protect user data from other users and here we will use the generic view from Django, namely UpdateView.

  • Then we define the Comment model that we will use model = Comment. Comment comes from the model class located in forums/models.py.

Screenshot_1.png

  • And we can define the fields we will use, in this class I will only use the fields = ['desc']. And the last we can define what template to render. here I will render forums / forum_update_comment.html '.


    We don't have a template forums / forum_update_comment.html. Now we will make it. the template is quite simple, you can see it as below:

forums/forum_update_comment.html

{% extends "base.html" %}

{% block title %} Edit Comment {% endblock %}

{% block content %}
<h2>Edit Comment</h2>
<form method="post">
    {% csrf_token %} // to protect the form
    {{ form.as_p }} // to render form
    <button type="submit" name="button">Submit</button>
</form>

{% endblock%}
  • In this template it's quite simple we only have a form{{ form.as_p }} that has been rendered automatically by Django and a forms protection obtained from {% csrf_token %}.

  • Connect edit comments with interface

now we have made the system and the URL. What is our concern now is how to connect them. For that, we need an interface so that users can use it as a trigger to run the function. We will make a link with the tag <a>. We will create the interface at forums/forum_detail.html. For more details, we can see the example below:

forums/forum_detail.html

    (html comment removed:  Display comment )
  {% for comment in object.comment_set.all %}
    <p>
        {{comment.desc}}
        {% if request.user == comment.user %} // protect data from other users
            <a href="{% url 'edit-comment' comment.id %}">Edit</a>
        {% endif %}
    </p>
  {% endfor %}
  • We will make protection on this interface. so the point is we will protect those comments so that they cannot be accessed by users who are not the owners. by checking like this {% if request.user == comment.user %}. request.user is the user who requests this interface and comment.user is the user of the comment that will be edited. If it matches then we will allow the user to access the comment edit interface.

  • We have created the URL that we discussed in the previous section now we will use the URL to edit comments. I put the URL in the tag <a> like this <a href="{% url 'edit-comment' comment.id %}">Edit</a>. edit-comment is the alias of the URL and here we will pass the comment.id parameter as the primary key. We can see in the picture below how the URL is rendered:

Screenshot_2.png

You can see in the picture above, the comment link above will only appear in the comments of the user who is logged in.


  • Edit comment

Now we will see if the system is running well, we will do a demonstration to check whether there is a mistake or not. we can see the results as shown below:

ezgif.com-video-to-gif (1).gif

  • we can see in the picture above we have successfully edited the comments of the user who owns the data. If you notice we are logged in with the milleduski1994 username and automatically we cannot edit comments that do not have user milleduski1994, This means we have succeeded in creating a protection system for user data.

  • So you don't confuse I will display the user who is logged in. we can see the picture below:

Screenshot_4.png


  • Display user in comment

Of course, the examples that I give can make you confused. Because we don't know who the user has given the comment, I will display the user in each of his comments. For more details you can see this example below:

forums/forum_detail.html

 {% for comment in object.comment_set.all %}
    <p>
        {{comment.desc}}
        {% if request.user == comment.user %}
            <a href="{% url 'edit-comment' comment.id %}">Edit</a>
        {% endif %}
        <br><span style="font-size: 12px;"><i>by {{comment.user}}</i></span>
    </p>
  {% endfor %}
  • We can display the username found on {{comment.user}}. comment is an alias variable that is formed when looping. the actual data source is in object.comment_set.all. If there is no error then we can see the picture below:

ezgif.com-video-to-gif (2).gif

We can see we have successfully displayed the name now you can distinguish from the user where the comment came from.

Curriculum

  • Forum app

django#1, django#2, django#3, django#4, django#5, django#6, django#7

Proof of work done

https://github.com/milleaduski/forums-django

Sort:  

Thank you for your contribution @duski.harahap.
After reviewing your contribution, we suggest you following points:

  • We suggest that in the next tutorial put other features besides editing posts and viewing comments.

  • Your tutorial is well structured and explained, but it is becoming a bit repetitive and slowly evolving. We suggest that you place new features that are interesting to the open source community.

  • Using GIFs to show results is definitely better than standard still images.

Looking forward to your upcoming tutorials.

Your contribution has been evaluated according to Utopian policies and guidelines, as well as a predefined set of questions pertaining to the category.

To view those questions and the relevant answers related to your post, click here.


Need help? Chat with us on Discord.

[utopian-moderator]

Thank you for your review, @portugalcoin! Keep up the good work!

Hi @duski.harahap!

Your post was upvoted by @steem-ua, new Steem dApp, using UserAuthority for algorithmic post curation!
Your post is eligible for our upvote, thanks to our collaboration with @utopian-io!
Feel free to join our @steem-ua Discord server

Congratulations @duski.harahap! You have completed the following achievement on the Steem blockchain and have been rewarded with new badge(s) :

You received more than 7000 upvotes. Your next target is to reach 8000 upvotes.

You can view your badges on your Steem Board and compare to others on the Steem Ranking
If you no longer want to receive notifications, reply to this comment with the word STOP

Vote for @Steemitboard as a witness to get one more award and increased upvotes!

Hey, @duski.harahap!

Thanks for contributing on Utopian.
We’re already looking forward to your next contribution!

Get higher incentives and support Utopian.io!
Simply set @utopian.pay as a 5% (or higher) payout beneficiary on your contribution post (via SteemPlus or Steeditor).

Want to chat? Join us on Discord https://discord.gg/h52nFrV.

Vote for Utopian Witness!

Coin Marketplace

STEEM 0.34
TRX 0.11
JST 0.034
BTC 66344.62
ETH 3214.81
USDT 1.00
SBD 4.37