pollvotecreateendpoint.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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={
  11. 'choices': request.data,
  12. },
  13. context={
  14. 'allowed_choices': poll.allowed_choices,
  15. 'choices': poll.choices,
  16. },
  17. )
  18. if not serializer.is_valid():
  19. return Response(
  20. {
  21. 'detail': serializer.errors['choices'][0],
  22. },
  23. status=400,
  24. )
  25. remove_user_votes(request.user, poll, serializer.data['choices'])
  26. set_new_votes(request, poll, serializer.data['choices'])
  27. add_acl_to_obj(request.user_acl, poll)
  28. serialized_poll = PollSerializer(poll).data
  29. poll.choices = list(map(presave_clean_choice, deepcopy(poll.choices)))
  30. poll.save()
  31. return Response(serialized_poll)
  32. def presave_clean_choice(choice):
  33. del choice['selected']
  34. return choice
  35. def remove_user_votes(user, poll, final_votes):
  36. removed_votes = []
  37. for choice in poll.choices:
  38. if choice['selected'] and choice['hash'] not in final_votes:
  39. poll.votes -= 1
  40. choice['votes'] -= 1
  41. choice['selected'] = False
  42. removed_votes.append(choice['hash'])
  43. if removed_votes:
  44. poll.pollvote_set.filter(voter=user, choice_hash__in=removed_votes).delete()
  45. def set_new_votes(request, poll, final_votes):
  46. for choice in poll.choices:
  47. if not choice['selected'] and choice['hash'] in final_votes:
  48. poll.votes += 1
  49. choice['votes'] += 1
  50. choice['selected'] = True
  51. poll.pollvote_set.create(
  52. category=poll.category,
  53. thread=poll.thread,
  54. voter=request.user,
  55. voter_name=request.user.username,
  56. voter_slug=request.user.slug,
  57. choice_hash=choice['hash'],
  58. )