pollmodel.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. start_date = models.DateTimeField()
  14. length = models.PositiveIntegerField(default=0)
  15. question = models.CharField(max_length=255)
  16. max_choices = models.PositiveIntegerField(default=0)
  17. _choices_cache = models.TextField(db_column='choices_cache')
  18. votes = models.PositiveIntegerField(default=0)
  19. vote_changing = models.BooleanField(default=False)
  20. public = models.BooleanField(default=False)
  21. class Meta:
  22. app_label = 'misago'
  23. @property
  24. def end_date(self):
  25. return self.start_date + timedelta(days=self.length)
  26. @property
  27. def over(self):
  28. if not self.length:
  29. return False
  30. return timezone.now() > self.end_date
  31. @property
  32. def choices_cache(self):
  33. try:
  34. return self._cache
  35. except AttributeError:
  36. pass
  37. try:
  38. self._cache = pickle.loads(base64.decodestring(self._choices_cache))
  39. except Exception:
  40. self._cache = []
  41. return self._cache
  42. @choices_cache.setter
  43. def choices_cache(self, choices):
  44. choices_cache = []
  45. for choice in choices:
  46. choices_cache.append({
  47. 'id': choice.pk,
  48. 'pk': choice.pk,
  49. 'name': choice.name,
  50. 'votes': choice.votes
  51. })
  52. self._cache = choices_cache
  53. self._choices_cache = base64.encodestring(pickle.dumps(choices_cache, pickle.HIGHEST_PROTOCOL))
  54. def retract_vote(self, votes):
  55. pass
  56. def make_vote(self, request, options):
  57. try:
  58. len(options)
  59. except TypeError:
  60. options = (options, )
  61. for option in self.option_set.all():
  62. if option.pk in options:
  63. self.votes += 1
  64. option.votes += 1
  65. option.save()
  66. self.vote_set.create(
  67. forum_id=self.forum_id,
  68. thread_id=self.thread_id,
  69. option=option,
  70. user=request.user,
  71. date=timezone.now(),
  72. ip=request.session.get_ip(request),
  73. agent=request.META.get('HTTP_USER_AGENT'),
  74. )
  75. self.choices_cache = [x for x in self.option_set.all()]