pollvote.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. id = serializers.SerializerMethodField()
  35. username = serializers.SerializerMethodField()
  36. slug = serializers.SerializerMethodField()
  37. voted_on = serializers.DateTimeField()
  38. class Meta:
  39. fields = [
  40. 'id',
  41. 'username',
  42. 'slug'
  43. 'voted_on',
  44. ]
  45. def get_id(self, obj):
  46. return obj['voter_id']
  47. def get_username(self, obj):
  48. return obj['voter_name']
  49. def get_slug(self, obj):
  50. return obj['voter_slug']