views.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. from django.shortcuts import render, get_object_or_404, redirect
  2. from django.http import HttpResponse
  3. from django.contrib.auth.decorators import login_required
  4. from django.contrib.auth.models import User
  5. from notifications.signals import notify
  6. from article.models import ArticlePost
  7. from .forms import CommentPost
  8. from .models import Comment
  9. @login_required(login_url='/user/login')
  10. def post_comment(request, article_id, parent_comment_id=None):
  11. article = get_object_or_404(ArticlePost, id=article_id)
  12. if request.method == 'POST':
  13. comment_form = CommentPost(data=request.POST)
  14. if comment_form.is_valid():
  15. new_comment_form = comment_form.save(commit=False)
  16. new_comment_form.article = article
  17. new_comment_form.user = request.user
  18. # 二级回复
  19. if parent_comment_id:
  20. parent_comment = Comment.objects.get(id=parent_comment_id)
  21. # 若回复层级超过二级,则转换为二级
  22. new_comment_form.parent_id = parent_comment.get_root().id
  23. # 被回复人
  24. new_comment_form.reply_to = parent_comment.user
  25. new_comment_form.save()
  26. if not parent_comment.user.is_superuser:
  27. notify.send(
  28. request.user,
  29. recipient=parent_comment.user,
  30. verb='回复了你',
  31. target=article,
  32. action_object=new_comment_form,
  33. )
  34. return HttpResponse('200 OK')
  35. new_comment_form.save()
  36. # 给管理员发送通知
  37. if not request.user.is_superuser:
  38. notify.send(
  39. request.user,
  40. recipient=User.objects.filter(is_superuser=1),
  41. verb='回复了你',
  42. target=article,
  43. action_object=new_comment_form,
  44. )
  45. return redirect(article)
  46. else:
  47. return HttpResponse('表单有错误,请重新填写')
  48. elif request.method == 'GET':
  49. comment_form = CommentPost()
  50. context = {
  51. 'comment_form': comment_form,
  52. 'article_id': article_id,
  53. 'parent_comment_id': parent_comment_id
  54. }
  55. return render(request, 'comment/reply.html', context)
  56. else:
  57. return HttpResponse('发表评论仅接受GET/POST请求')