pollvote.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. from rest_framework import serializers
  2. from django.urls import reverse
  3. from django.utils.translation import ugettext as _
  4. from django.utils.translation import ungettext
  5. __all__ = [
  6. 'NewVoteSerializer',
  7. 'PollVoteSerializer',
  8. ]
  9. class NewVoteSerializer(serializers.Serializer):
  10. choices = serializers.ListField(
  11. child=serializers.CharField(),
  12. )
  13. def validate_choices(self, data):
  14. if len(data) > self.context['allowed_choices']:
  15. message = ungettext(
  16. "This poll disallows voting for more than %(choices)s choice.",
  17. "This poll disallows voting for more than %(choices)s choices.",
  18. self.context['allowed_choices']
  19. )
  20. raise serializers.ValidationError(
  21. message % {'choices': self.context['allowed_choices']},
  22. )
  23. valid_choices = [c['hash'] for c in self.context['choices']]
  24. clean_choices = []
  25. for choice in data:
  26. if choice in valid_choices and choice not in clean_choices:
  27. clean_choices.append(choice)
  28. if len(clean_choices) != len(data):
  29. raise serializers.ValidationError(
  30. _("One or more of poll choices were invalid."),
  31. )
  32. if not len(clean_choices):
  33. raise serializers.ValidationError(
  34. _("You have to make a choice."),
  35. )
  36. return clean_choices
  37. class PollVoteSerializer(serializers.Serializer):
  38. voted_on = serializers.DateTimeField()
  39. username = serializers.SerializerMethodField()
  40. url = serializers.SerializerMethodField()
  41. class Meta:
  42. fields = [
  43. 'voted_on',
  44. 'username',
  45. 'url',
  46. ]
  47. def get_username(self, obj):
  48. return obj['voter_name']
  49. def get_url(self, obj):
  50. if obj['voter_id']:
  51. return reverse(
  52. 'misago:user', kwargs={
  53. 'pk': obj['voter_id'],
  54. 'slug': obj['voter_slug'],
  55. }
  56. )