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
from.models import Article, Comment
admin.site.register(Article)
admin.sitce.register(Commnet)
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',)
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)
<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'),
]
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)
<h4>댓글 목록</h4>
<ul>
{% for comment in comments %}
<li>{{ comment.content }}</li>
{% endfor %}
</ul>
urlpatterns = [
path('<int:article_pk>/comments/<int:comment_pk>/delete/', views.comments_delete, name='comments_delete'),
]
def comments_delete(request, article_pk, comment_pk):
comment = Comment.objects.get(pk=comment_pk)
comment.delete()
return redirect('articles:detail', article_pk)
<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 %}