poll.py 5.6 KB

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