DB
DB에 대하여(6)_댓글 READ & DELETE (feat. Django)
데이터분석가 이채은
2024. 4. 21. 09:00
1. 댓글 READ 구현
detail view 함수에서 전체 댓글 데이터를 조회
# articles/views.py
from .models import Article, Comment
def detail(request, pk):
article = Article.objects.get(pk=pk)
comment_form = CommentForm()
comments = article.comment_set.all()
context = {
'article': article,
'comment_form': comment_form,
'comments': comments,
}
return render(request, 'articles/detail.html', context)
<!-- articles/detail.html -->
<h4>댓글 목록</h4>
<ul>
{% for comment in comments %}
<li>{{ comment.content }}</li>
{% endfor %}
</ul>
2. 댓글 DELETE 구현
댓글 삭제 url 작성
# articles/urls.py
app_name = 'articles'
urlpatterns = [
...,
path('<int:article_pk>/comments/<int:comment_pk>/delete/',
views.comments_delete,
name='comments_delete'
),
]
댓글 삭제 view 함수 정의
# articles/views.py
from .models import Article, Comment
def comments_delete(request, article_pk, comment_pk):
comment = Comment.objects.get(pk=comment_pk)
comment.delete()
return redirect('articles:detail', article_pk)
<!-- articles/detail.html -->
<ul>
{% for comment in comments %}
<li>
{{ comment.content }}
<form action="{% url 'articles:comments_delete' article.pk comment.pk %}" method="POST">
{% csrf_token %}
<input type="submit" value="DELETE">
</form>
</li>
{% endfor %}
</ul>
참고
1. admin site 등록
Comment 모델을 admin site에 등록해 CRUD 동작 확인하기
# articles/admin.py
from .models import Article, Comment
admin.site.register(Article)
admin.site.register(Comment)
2. 댓글이 없는 경우 대체 콘텐츠 출력
DTL 'for empty' 태그 사용
<!-- articles/detail.html -->
{% for comment in comments %}
<li>
{{ comment.content }}
<form action="{% url 'articles:comments_delete' article.pk comment.pk %}" method="POST">
{% csrf_token %}
<input type="submit" value="DELETE">
</form>
</li>
{% empty %}
<p>댓글이 없어요..</p>
{% endfor %}
3. 댓글 개수 출력하기
DTL filter - 'length' 사용
{{ comments|length }}
{{ article.comment_set.all|length }}
QuerysetAPI - 'count()' 사용
{{ article.comment_set.count }}