You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Django/doc/comments/urls.py

43 lines
1.3 KiB

from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404
from django.views.generic import View
from blog.models import Article
from .models import Comment
from .forms import CommentForm
class CommentPostView(LoginRequiredMixin, View):
"""
负责处理评论提交
"""
def post(self, request, article_id):
# 获取目标文章
article = get_object_or_404(Article, pk=article_id)
form = CommentForm(request.POST)
if form.is_valid():
# 获取评论内容
body = form.cleaned_data['body'].strip()
parent_id = form.cleaned_data.get('parent_comment_id')
comment = Comment()
comment.article = article
comment.author = request.user
comment.body = body
# 判断是否是子评论(回复)
if parent_id:
try:
parent_comment = Comment.objects.get(id=parent_id)
comment.parent_comment = parent_comment
except Comment.DoesNotExist:
pass
comment.save()
# 评论成功后返回文章页面
return HttpResponseRedirect(article.get_absolute_url())