move.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. from django.core.exceptions import PermissionDenied
  2. from django.utils.translation import gettext as _
  3. from rest_framework.response import Response
  4. from ...serializers import MovePostsSerializer
  5. def posts_move_endpoint(request, thread, viewmodel):
  6. if not thread.acl["can_move_posts"]:
  7. raise PermissionDenied(_("You can't move posts in this thread."))
  8. serializer = MovePostsSerializer(
  9. data=request.data,
  10. context={
  11. "request": request,
  12. "settings": request.settings,
  13. "thread": thread,
  14. "viewmodel": viewmodel,
  15. },
  16. )
  17. if not serializer.is_valid():
  18. if "new_thread" in serializer.errors:
  19. errors = serializer.errors["new_thread"]
  20. else:
  21. errors = list(serializer.errors.values())[0]
  22. # Fix for KeyError - errors[0]
  23. try:
  24. return Response({"detail": errors[0]}, status=400)
  25. except KeyError:
  26. return Response({"detail": list(errors.values())[0][0]}, status=400)
  27. new_thread = serializer.validated_data["new_thread"]
  28. for post in serializer.validated_data["posts"]:
  29. post.move(new_thread)
  30. post.save()
  31. thread.synchronize()
  32. thread.save()
  33. new_thread.synchronize()
  34. new_thread.save()
  35. thread.category.synchronize()
  36. thread.category.save()
  37. if thread.category != new_thread.category:
  38. new_thread.category.synchronize()
  39. new_thread.category.save()
  40. return Response({})