class Comment(CommonModel):
content=models.TextField()
post=models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE)
def __str__(self):
return f'{self.content}-{self.post}'
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ("content",)
def save(self):
comment = super().save(commit=False)
return comment
views.py에서 form을 저장한 뒤 comment에 해당 게시물의 데이터를 추가하고 DB에 저장해야 하기 때문에 form.save()
는 DB에 저장하지 않기 위해 사용
from django.urls import path
from . import views
app_name = "posts"
urlpatterns = [
# 게시물
...
# 댓글
path("comments/write/<int:post_id>/", views.comment_create, name="comment-create"),
]
# 댓글 생성
def comment_create(request, post_id):
if request.method == "POST":
form = CommentForm(request.POST)
post = Post.objects.get(id=post_id) # 댓글이 어떤 게시물의 댓글인지 확인
if not post:
return redirect("posts:list")
if form.is_valid():
comment = form.save()
comment.post = post
comment.save()
messages.success(request, "Post reviewed")
return redirect("posts:detail", post_id=post.id)
else:
form=CommentForm()
return render(request, "posts/comment_form.html", {"form": form})