pollmodel.py 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. from datetime import timedelta
  2. from django.db import models
  3. from django.utils import timezone
  4. import base64
  5. try:
  6. import cPickle as pickle
  7. except ImportError:
  8. import pickle
  9. class Poll(models.Model):
  10. forum = models.ForeignKey('Forum')
  11. thread = models.OneToOneField('Thread', primary_key=True)
  12. user = models.ForeignKey('User', null=True, blank=True, on_delete=models.SET_NULL)
  13. user_name = models.CharField(max_length=255, null=True, blank=True)
  14. user_slug = models.SlugField(max_length=255, null=True, blank=True)
  15. start_date = models.DateTimeField()
  16. length = models.PositiveIntegerField(default=0)
  17. question = models.CharField(max_length=255)
  18. max_choices = models.PositiveIntegerField(default=0)
  19. _choices_cache = models.TextField(db_column='choices_cache')
  20. votes = models.PositiveIntegerField(default=0)
  21. vote_changing = models.BooleanField(default=False)
  22. public = models.BooleanField(default=False)
  23. class Meta:
  24. app_label = 'misago'
  25. @property
  26. def end_date(self):
  27. return self.start_date + timedelta(days=self.length)
  28. @property
  29. def over(self):
  30. if not self.length:
  31. return False
  32. return timezone.now() > self.end_date
  33. @property
  34. def choices_cache(self):
  35. try:
  36. return self._cache
  37. except AttributeError:
  38. pass
  39. try:
  40. self._cache = pickle.loads(base64.decodestring(self._choices_cache))
  41. except Exception:
  42. self._cache = []
  43. return self._cache
  44. @choices_cache.setter
  45. def choices_cache(self, choices):
  46. choices_cache = []
  47. for choice in choices:
  48. choices_cache.append({
  49. 'id': choice.pk,
  50. 'pk': choice.pk,
  51. 'name': choice.name,
  52. 'votes': choice.votes
  53. })
  54. self._cache = choices_cache
  55. self._choices_cache = base64.encodestring(pickle.dumps(choices_cache, pickle.HIGHEST_PROTOCOL))
  56. def retract_vote(self, votes):
  57. pass
  58. def make_vote(self, request, options):
  59. try:
  60. len(options)
  61. except TypeError:
  62. options = (options, )
  63. for option in self.option_set.all():
  64. if option.pk in options:
  65. self.votes += 1
  66. option.votes += 1
  67. option.save()
  68. self.vote_set.create(
  69. forum_id=self.forum_id,
  70. thread_id=self.thread_id,
  71. option=option,
  72. user=request.user,
  73. user_name=request.user.username,
  74. user_slug=request.user.slug,
  75. date=timezone.now(),
  76. ip=request.session.get_ip(request),
  77. agent=request.META.get('HTTP_USER_AGENT'),
  78. )
  79. self.choices_cache = [x for x in self.option_set.all()]