poll.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. from rest_framework import serializers
  2. from django.urls import reverse
  3. from django.utils.crypto import get_random_string
  4. from django.utils.translation import ugettext as _
  5. from django.utils.translation import ungettext
  6. from misago.threads.models import Poll
  7. __all__ = [
  8. 'PollSerializer',
  9. 'NewPollSerializer',
  10. 'PollChoiceSerializer',
  11. ]
  12. MAX_POLL_OPTIONS = 16
  13. class PollSerializer(serializers.ModelSerializer):
  14. acl = serializers.SerializerMethodField()
  15. choices = serializers.SerializerMethodField()
  16. api = serializers.SerializerMethodField()
  17. url = serializers.SerializerMethodField()
  18. class Meta:
  19. model = Poll
  20. fields = (
  21. 'id',
  22. 'poster_name',
  23. 'posted_on',
  24. 'length',
  25. 'question',
  26. 'allowed_choices',
  27. 'allow_revotes',
  28. 'votes',
  29. 'is_public',
  30. 'acl',
  31. 'choices',
  32. 'api',
  33. 'url',
  34. )
  35. def get_api(self, obj):
  36. return {
  37. 'index': obj.get_api_url(),
  38. 'votes': obj.get_votes_api_url(),
  39. }
  40. def get_url(self, obj):
  41. return {
  42. 'poster': self.get_poster_url(obj),
  43. }
  44. def get_poster_url(self, obj):
  45. if obj.poster_id:
  46. return reverse('misago:user', kwargs={
  47. 'slug': obj.poster_slug,
  48. 'pk': obj.poster_id,
  49. })
  50. else:
  51. return None
  52. def get_acl(self, obj):
  53. try:
  54. return obj.acl
  55. except AttributeError:
  56. return None
  57. def get_choices(self, obj):
  58. return obj.choices
  59. class EditPollSerializer(serializers.ModelSerializer):
  60. length = serializers.IntegerField(required=True, min_value=0, max_value=180)
  61. question = serializers.CharField(required=True, max_length=255)
  62. allowed_choices = serializers.IntegerField(required=True, min_value=1)
  63. choices = serializers.ListField(
  64. allow_empty=False,
  65. child=serializers.DictField(),
  66. )
  67. class Meta:
  68. model = Poll
  69. fields = (
  70. 'length',
  71. 'question',
  72. 'allowed_choices',
  73. 'allow_revotes',
  74. 'choices',
  75. )
  76. def validate_choices(self, choices):
  77. clean_choices = list(map(self.clean_choice, choices))
  78. # generate hashes for added choices
  79. choices_map = {}
  80. for choice in self.instance.choices:
  81. choices_map[choice['hash']] = choice
  82. final_choices = []
  83. for choice in clean_choices:
  84. if choice['hash'] in choices_map:
  85. choices_map[choice['hash']].update({
  86. 'label': choice['label']
  87. })
  88. final_choices.append(choices_map[choice['hash']])
  89. else:
  90. choice.update({
  91. 'hash': get_random_string(12),
  92. 'votes': 0
  93. })
  94. final_choices.append(choice)
  95. self.validate_choices_num(final_choices)
  96. return final_choices
  97. def clean_choice(self, choice):
  98. clean_choice = {
  99. 'hash': choice.get('hash', get_random_string(12)),
  100. 'label': choice.get('label', ''),
  101. }
  102. serializer = PollChoiceSerializer(data=clean_choice)
  103. if not serializer.is_valid():
  104. raise serializers.ValidationError(_("One or more poll choices are invalid."))
  105. return serializer.data
  106. def validate_choices_num(self, choices):
  107. total_choices = len(choices)
  108. if total_choices < 2:
  109. raise serializers.ValidationError(_("You need to add at least two choices to a poll."))
  110. if total_choices > MAX_POLL_OPTIONS:
  111. message = ungettext(
  112. "You can't add more than %(limit_value)s option to a single poll (added %(show_value)s).",
  113. "You can't add more than %(limit_value)s options to a single poll (added %(show_value)s).",
  114. MAX_POLL_OPTIONS)
  115. raise serializers.ValidationError(message % {
  116. 'limit_value': MAX_POLL_OPTIONS,
  117. 'show_value': total_choices
  118. })
  119. def validate(self, data):
  120. if data['allowed_choices'] > len(data['choices']):
  121. raise serializers.ValidationError(
  122. _("Number of allowed choices can't be greater than number of all choices."))
  123. return data
  124. def update(self, instance, validated_data):
  125. if instance.choices:
  126. self.update_choices(instance, validated_data['choices'])
  127. return super(EditPollSerializer, self).update(instance, validated_data)
  128. def update_choices(self, instance, cleaned_choices):
  129. removed_hashes = []
  130. final_hashes = [c['hash'] for c in cleaned_choices]
  131. for choice in instance.choices:
  132. if choice['hash'] not in final_hashes:
  133. instance.votes -= choice['votes']
  134. removed_hashes.append(choice['hash'])
  135. if removed_hashes:
  136. instance.pollvote_set.filter(choice_hash__in=removed_hashes).delete()
  137. class NewPollSerializer(EditPollSerializer):
  138. class Meta:
  139. model = Poll
  140. fields = (
  141. 'length',
  142. 'question',
  143. 'allowed_choices',
  144. 'allow_revotes',
  145. 'is_public',
  146. 'choices',
  147. )
  148. def validate_choices(self, choices):
  149. clean_choices = list(map(self.clean_choice, choices))
  150. self.validate_choices_num(clean_choices)
  151. for choice in clean_choices:
  152. choice.update({
  153. 'hash': get_random_string(12),
  154. 'votes': 0
  155. })
  156. return clean_choices
  157. class PollChoiceSerializer(serializers.Serializer):
  158. hash = serializers.CharField(required=True, min_length=12, max_length=12)
  159. label = serializers.CharField(required=True, max_length=255)