Blog with Django (Codemy.com) - 34 Add Comment

이다연·2021년 3월 31일
0

Django

목록 보기
27/33

Anyone can leave a comment!
If you want only authenticated users leave it, use JS

1. templates

Add Comment link

article_details.html

<a href=""> Add Comment </a>

create a new template add_comment.html
copy and paste the editing form at add_post.html

{% extends 'base.html' %}
{% block title %} New Comment {% endblock %}

{% block content %}

<h1> Add Comment  </h1>
<br/>

<div class="form-group">
    <form method="POST">
        {% csrf_token %}
        {{ form.as_p }}
        <br/>
        <button class="btn btn-secondary"> Add Comment </button>
    </form>
</div>

{% endblock %}

2. Views

from .models import Comment

3. urls

from .views import AddCommentView

 path('article/<int:pk>/comment', 
 	AddCommentView.as_view(), name="add_comment"),

4. add url into template

article_details.html

<a href="{% url 'add_comment' post.pk %}"> Add Comment </a>

we need to pass in post.pk so that urls.py knows where to go.

we still need to fix a few things. such as user doesn't need to select a post to comment.

5. forms.py

we need to create a form for comment, to get rid of select option

attrs={'class': 'form-control'}), form contorl is to be bootsrapified

from .models import Comment
	class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = ('name', 'body')

        widgets = {
            'name': forms.TextInput(attrs={'class': 'form-control', 'value': '', 'id': 'users_id'}),
            'body': forms.Textarea(attrs={'class': 'form-control'}),
        }

6. views

when using a form, we don't need to designate fields. fields is commented out

It's directing to home, but we want to comeback to current post. we will tackle this later.

from .forms import CommentForm

class AddCommentView(CreateView):
    model = Comment
    form_class = CommentForm
    template_name = 'add_comment.html'
    #fields = '__all__'
    success_url = reverse_lazy('home')
	

7. views

we want to associate the comment with post id.
pk in the url is passed in as kwargs. we can access pk and assign it

    def form_valid(self, form):
        form.instance.post_id = self.kwargs['pk']
        return super().form_valid(form)

8. templates

I added authenticated user's name automatically added using JS.

{% extends 'base.html' %}
{% block title %} New Comment {% endblock %}

{% block content %}

<h1> Add Comment  </h1>
<br/>

<div class="form-group">
    <form method="POST">
        {% csrf_token %}
   {% if user.is_authenticated %}
        {{ form.media }}
   {% endif %}
        {{ form.as_p }}
        <br/>
        <button class="btn btn-secondary"> Add Comment </button>
    </form>
</div>

<script>
    var name = "{{ user.username }}";
    document.getElementById("users_id").value
             = name;

</script>

{% endblock %}

9. views: redirecting to current page

add function under class

class AddCommentView(CreateView):
~
    def get_success_url(self):
        return reverse_lazy('article-detail', kwargs={'pk': self.kwargs['pk']})

10. Automatically added Username

We can associate username with the comment by configuring forms.py and template with JS.

If user is not logged in, we wouldn't know their username. We can set a form field but in that case, user can modify their name too.

I decided to hard code 'Anonymous User' into name.

forms.py

        widgets = {
            'name': forms.TextInput(attrs={'class': 'form-control', 'value': '', 'id': 'users_id', 'type':'hidden'}),

template

<div class="form-group">
    <form method="POST">
        {% csrf_token %}
   {% if user.is_authenticated %}
        {{ form.media }}
        {{ form.as_p }}

   {% else %}
         {{ form.as_p }}
   {% endif %}
        <br/>
        <button class="btn btn-secondary"> Add Comment </button>
    </form>
</div>
{% if user.is_authenticated %}
    <script>
        var name = "{{ user.username }}";
        document.getElementById("users_id").value
                 = name;

    </script>
{% else %}
    <script>
        var name = "Anonymous User";
        document.getElementById("users_id").value
                 = name;

    </script>

{% endif %}

In case anonymous user wants to leave a comment.

profile
Dayeon Lee | Django & Python Web Developer

8개의 댓글

comment-user-thumbnail
2023년 10월 16일

I had been stuck on implementing this for days in my own site. I had heard of "kwargs" before, but I had never used it. Turns out, the form_valid section was all I needed. Thank you so much for showing us this! wordle

1개의 답글
comment-user-thumbnail
2023년 10월 16일

For days, I was unable to move forward with this on my own website tunnel rush . "Kwargs" were a term I had heard of but never used. It turned out that all I required was the form_valid portion. We really appreciate you showing this to us.

답글 달기
comment-user-thumbnail
2023년 11월 14일

retro bowl college is indeed a popular mobile game that combines elements of football management and on-field decision-making, all presented in a nostalgic retro aesthetic. It provides a simplified and enjoyable experience for players who want to take on the role of a football coach and quarterback.

답글 달기
comment-user-thumbnail
2023년 11월 21일

Make sure that you really intend to book a Call Girl in Aerocity otherwise try to be away from us. Girls are professionally trained to behave gently and appropriately as per the occasion of a location.

답글 달기
comment-user-thumbnail
2023년 12월 7일

As a night rider, I am well-mannered and professional too. If you want to enjoy the dancing moves and my maintained figure, then the best way is to hire my Independent Call Girls in Panaji. There are many clubs in Panaji and nothing can be better than entering a club with a sizzling and hot girl.

답글 달기
comment-user-thumbnail
2024년 1월 17일

A person always shows interest Cuncolim Call Girls that he finds genuine and result oriented. No one will ever invest their time and money in agencies or services that have a poor reputation or lack the trust of the public.

답글 달기
comment-user-thumbnail
2024년 4월 5일

Nothing of this sort happens when you are with our independent Delhi escorts. They feel flattered in the first place that you have chosen her among a long list of gorgeous and hot models.
Daya Basti Call Girls
Call Girls in Deenpur
Sidhartha Nagar Escorts
Escorts in Siraspur
Soami Nagar Escorts Service

답글 달기