pollvote.py 1.9 KB

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