from django.shortcuts import render, get_object_or_404, redirect from django.http import HttpResponse from django.contrib.auth.decorators import login_required from article.models import ArticlePost from .forms import CommentPost from .models import Comment @login_required(login_url='/user/login') def post_comment(request, article_id, parent_comment_id=None): article = get_object_or_404(ArticlePost, id=article_id) if request.method == 'POST': comment_form = CommentPost(data=request.POST) if comment_form.is_valid(): new_comment_form = comment_form.save(commit=False) new_comment_form.article = article new_comment_form.user = request.user # 二级回复 if parent_comment_id: parent_comment = Comment.objects.get(id=parent_comment_id) # 若回复层级超过二级,则转换为二级 new_comment_form.parent_id = parent_comment.get_root().id # 被回复人 new_comment_form.reply_to = parent_comment.user new_comment_form.save() return HttpResponse('200 OK') new_comment_form.save() return redirect(article) else: return HttpResponse('表单有错误,请重新填写') elif request.method == 'GET': comment_form = CommentPost() context = { 'comment_form': comment_form, 'article_id': article_id, 'parent_comment_id': parent_comment_id } return render(request, 'comment/reply.html', context) else: return HttpResponse('发表评论仅接受GET/POST请求')