본문 바로가기
Django

[Django] 댓글 CRUD(3) - 댓글 생성(C)

by 기록하는_사람 2022. 12. 21.

댓글 생성

📌 댓글 생성

① detail.html에 댓글 생성 input 만들기.

<h1>DETAIL PAGE</h1>

<h3>{{ b.name }}</h3>
<b>지은이</b><input type="text" value="{{ b.writer }}" disabled><br><br>
<b>조회수</b><input type="text" value="{{ b.hit }}" disabled><br><br>
<b>내용</b><br><textarea cols="80" rows="8" disabled>{{ b.content }}</textarea><br><br>

<a href="{% url 'index' %}"><button>HOME</button></a>
<a href="{% url 'update' b.id %}"><button>MOD</button></a>
<a href="{% url 'delete' b.id %}"><button>DEL</button></a>

<hr>
<form method="post" action="{% url 'creply' b.id %}">
    {% csrf_token %}
    <input name="nnick" type="text" placeholder="NICKNAME" size="7">
    <input name="ncomment" type="text" placeholder="COMMENT" size="30">
    <button>INPUT</button>
</form>

<hr>
{% for i in rset %}
    <b>{{ i.nick }}</b>
    <input type="text" value="{{ i.comment }}" disabled size="30">
    <br>
{% empty %}
    <h4>댓글 없음.</h4>
{% endfor %}

 

② books/urls.py

from django.urls import path
from . import views

urlpatterns = [
    path('index/', views.index, name="index"),
    path('detail/<bpk>', views.detail, name="detail"),
    path('delete/<bpk>', views.delete, name="delete"),
    path('create/', views.create, name="create"),
    path('update/<bpk>', views.update, name="update"),
    path('creply/<bpk>', views.creply, name="creply")
]

 

③ books/views.py 

...
def creply(request, bpk):
    b = Books.objects.get(id=bpk)
    n = request.POST.get("nnick")
    c = request.POST.get("ncomment")
    Reply(b=b, nick=n, comment=c).save()
    return redirect("detail", bpk)

 

댓글 생성 - 결과

📌 댓글 생성 - 결과

댓글