[Django] 댓글기능 CRUD

송왕구·2023년 4월 11일
0

Django

목록 보기
9/9

💁‍♀️ 사전준비

  • Comment 모델 정의
  • articles/models.py
class Comment(models.Model):
	article = models.ForeignKey(Article, on_delete=models.CASCADE)
    content = models.CharField(max_length=200)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    def __str__(self):
    return self.content

  • admin site 등록
  • articles/admin.py
from.models import Article, Comment

admin.site.register(Article)
admin.sitce.register(Commnet)



💁‍♀️ CREATE

  • 유저에게 댓글을 받기 위한 CommentForm
  • articles/forms.py
from django import forms
from .models import Article, Comment

class ArticleForm(forms.ModelForm):
	model = Article
    exclude = ('user',)
    
class CommentForm(forms.ModelForm):
	class Meta:
    	model = Comment
        exclude=('article',)

  • detail 페이지에 CommentForm 출력
  • articles/views.py
from django.shortcuts import render, redirect
from .models import Article, Comment
from .forms import ArticleForm, CommentForm

def detail(request, pk):
	article = Article.objects.get(pk=pk)
    comment_form = CommentForm()
    context = {
    	'article':article,
    	'comment_form':comment_form,
    }
   	return redner(request, 'articles/detail.html', context)
def comments_create(request, pk):
	article = Article.objects.get(pk=pk)
    comment_form = CommentForm(request.POST)
    if comment_form.is_valid():
    	comment = comment_form.save(commit=False)
        comment.article = article
        comment.save()
    return redirect('articles:detail', article.pk)

  • articles/detail.html
<form action='{% url 'articles:comments_create'} article.pk %}' method = 'POST'>
	{% crsf_token %}
    {{ comment_form }}
	<input type='submit'>
</form>

-articles/urls.py

urlpatterns = [
	path('<int:pk>/comments/', views.comments_create, name='comments_create'),
]



💁‍♀️ READ

  • articles/views.py
def detail(request, pk):
    article = Article.objects.get(pk=pk)
    comment_form = CommentForm()
    comments = article.comments.all()
    context = {
        'article': article,
        'comment_form':comment_form,
        'comments':comments,
        }
    return render(request, 'articles/detail.html', context)

  • detail.html
<h4>댓글 목록</h4>
    <ul>
      {% for comment in comments %}
        <li>{{ comment.content }}</li>
      {% endfor %}

    </ul>



💁‍♀️ DELETE

  • articles/url.py
urlpatterns = [
     path('<int:article_pk>/comments/<int:comment_pk>/delete/', views.comments_delete, name='comments_delete'),
]

  • article/views.py
def comments_delete(request, article_pk, comment_pk):
    comment = Comment.objects.get(pk=comment_pk)
    comment.delete()
    return redirect('articles:detail', article_pk)

  • detail.html
    <h4>댓글 목록</h4>
    <ul>
      {% for comment in comments %}
        <li>{{ comment.content }}</li>
        <form action="{% url 'articles:comments_delete' article.pk comment.pk %}" method='POST'>
          {% csrf_token %}
          <input type="submit" value='DELETE'>
        </form>
      {% endfor %}
profile
다른 사람들처럼 거창하게 어떤 개발자가 되고 싶은 생각은 없습니다. 그냥 놀듯이 내가 원하는건 모두 할 수 있고 재미있는 삶을 욕망합니다.

0개의 댓글