pollvotecreateendpoint.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. from copy import deepcopy
  2. from rest_framework.response import Response
  3. from misago.acl.objectacl import add_acl_to_obj
  4. from misago.threads.permissions import allow_vote_poll
  5. from misago.threads.serializers import PollSerializer, NewVoteSerializer
  6. def poll_vote_create(request, thread, poll):
  7. poll.make_choices_votes_aware(request.user)
  8. allow_vote_poll(request.user_acl, poll)
  9. serializer = NewVoteSerializer(
  10. data={"choices": request.data},
  11. context={"allowed_choices": poll.allowed_choices, "choices": poll.choices},
  12. )
  13. if not serializer.is_valid():
  14. return Response({"detail": serializer.errors["choices"][0]}, status=400)
  15. remove_user_votes(request.user, poll, serializer.data["choices"])
  16. set_new_votes(request, poll, serializer.data["choices"])
  17. add_acl_to_obj(request.user_acl, poll)
  18. serialized_poll = PollSerializer(poll).data
  19. poll.choices = list(map(presave_clean_choice, deepcopy(poll.choices)))
  20. poll.save()
  21. return Response(serialized_poll)
  22. def presave_clean_choice(choice):
  23. del choice["selected"]
  24. return choice
  25. def remove_user_votes(user, poll, final_votes):
  26. removed_votes = []
  27. for choice in poll.choices:
  28. if choice["selected"] and choice["hash"] not in final_votes:
  29. poll.votes -= 1
  30. choice["votes"] -= 1
  31. choice["selected"] = False
  32. removed_votes.append(choice["hash"])
  33. if removed_votes:
  34. poll.pollvote_set.filter(voter=user, choice_hash__in=removed_votes).delete()
  35. def set_new_votes(request, poll, final_votes):
  36. for choice in poll.choices:
  37. if not choice["selected"] and choice["hash"] in final_votes:
  38. poll.votes += 1
  39. choice["votes"] += 1
  40. choice["selected"] = True
  41. poll.pollvote_set.create(
  42. category=poll.category,
  43. thread=poll.thread,
  44. voter=request.user,
  45. voter_name=request.user.username,
  46. voter_slug=request.user.slug,
  47. choice_hash=choice["hash"],
  48. )