move.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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={"request": request, "thread": thread, "viewmodel": viewmodel},
  11. )
  12. if not serializer.is_valid():
  13. if "new_thread" in serializer.errors:
  14. errors = serializer.errors["new_thread"]
  15. else:
  16. errors = list(serializer.errors.values())[0]
  17. # Fix for KeyError - errors[0]
  18. try:
  19. return Response({"detail": errors[0]}, status=400)
  20. except KeyError:
  21. return Response({"detail": list(errors.values())[0][0]}, status=400)
  22. new_thread = serializer.validated_data["new_thread"]
  23. for post in serializer.validated_data["posts"]:
  24. post.move(new_thread)
  25. post.save()
  26. thread.synchronize()
  27. thread.save()
  28. new_thread.synchronize()
  29. new_thread.save()
  30. thread.category.synchronize()
  31. thread.category.save()
  32. if thread.category != new_thread.category:
  33. new_thread.category.synchronize()
  34. new_thread.category.save()
  35. return Response({})