Source

django-ajax-poll / poll / models.py

Full commit
Guillaume Piot 663d115 














































































from django.db import models
from django.utils.translation import ugettext_lazy as _
import datetime

now = datetime.datetime.now()
today = datetime.date(year=now.year, month=now.month, day=now.day)

class poll(models.Model):
	question =	 models.CharField(_('Question'),max_length=250)
	answers =	models.TextField(_('Answers'), help_text=_('Please enter one answer per line.'))
	publish_date = models.DateField(_('Publish date'))
	publish =	models.BooleanField(_("Publish"),max_length=1)

	def __unicode__(self):
		return u'%s' % (self.question)
	class Meta:
		verbose_name  = 'Poll'
		verbose_name_plural = 'Polls'
		
	def get_answers(self):
		answers = self.answers.splitlines(True)
		a_list = []
		i=1
		for a in answers:
			a_list.append((i, a.strip()))
			i = i+1

		return a_list
		
	def get_answers_stat(self):
		import operator
		from decimal import *
		answers = self.answers.splitlines(True)
		a_list = []
		i=1
		
		for a in answers:
			stat = poll_submission.objects.filter(poll_ref=self, answer_id=str(i))
			
			a_list.append((i, a.strip(), len(stat)))
			i = i+1
		final_list = sorted(a_list, key=operator.itemgetter(2), reverse=True)
		
		#repreocess the list using the highest value to generate pro-rata for bar graph
		highest = final_list[0][2]
		
		#Enter the div of the width containing the bar graph
		div_width = 200
		i=0
		final_list2 = []

		for a in answers:
			if highest > 0:
				width = Decimal(final_list[i][2])/Decimal(highest) * Decimal(div_width)
				width = Decimal(width).quantize(Decimal('1.'))
				final_list2.append((final_list[i][0],final_list[i][1],final_list[i][2],width))
				i = i+1 
			
   
		return final_list2
		
	def published(self):
		if self.publish == False:
			return False
		if self.publish_date > today:
			return False
		return True	 


class poll_submission(models.Model):
	poll_ref = models.ForeignKey(poll)
	answer_id = models.CharField(_('Answer id'),max_length=10)
	answer_text = models.CharField(_('Answer text'),max_length=250)
	submit_date = models.DateTimeField(_('Submit date'), auto_now=True)

	def __unicode__(self):
		return u'%s' % (self.question)
	class Meta:
		verbose_name  = 'Poll submission'
		verbose_name_plural = 'Polls submissions'