poll.py 5.7 KB

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