Anonymous avatar Anonymous committed 663d115

initial commit'

;

Comments (0)

Files changed (20)

Binary file added.

Empty file added.

Binary file added.

+from gpoll.poll.models import *
+from django.contrib import admin 
+from django.core.urlresolvers import reverse
+from django.utils.translation import ugettext_lazy as _            
+
+class polladmin(admin.ModelAdmin):
+	actions = ['delete_selected']
+	list_filter = ['publish']
+	list_display = ['question', 'list_answers', 'publish', 'publish_date', 'download_answers']
+	
+	fieldsets = (
+		('Content', {
+			'fields': ( 'question', 'answers', 'publish', 'publish_date')
+		}),
+		
+	)
+	
+	
+	def list_answers(self, obj):
+		answers = obj.answers.splitlines(True)
+		a_list = ""
+		for a in answers:
+			a_list += '%s<br />' % a.strip()
+		return a_list
+	list_answers.short_description = 'Answers' 
+	list_answers.allow_tags = True
+	
+	def download_answers(self, obj):
+		
+		return '<a href="%s">%s</a>' % (reverse('poll_export_answers',kwargs={'object_id':obj.id}), 'Download CSV')
+	download_answers.short_description = 'Data dump' 
+	download_answers.allow_tags = True
+admin.site.register(poll, polladmin) 
+
+class pollsubmissionadmin(admin.ModelAdmin):
+	list_filter = ['poll_ref']
+	list_display = ['poll_ref', 'answer_id', 'answer_text', 'submit_date']
+	actions = ['delete_selected']
+	
+	
+
+admin.site.register(poll_submission, pollsubmissionadmin) 
+
+   

Binary file added.

+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'

Binary file added.

poll/templates/default.html

+{% load poll_tags %}<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en" >
+<head>
+<title>Django Ajax Poll</title>
+<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
+<meta name="description" content=""/>
+<meta name="keywords" content=""/>
+
+
+
+<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
+
+
+
+</head>
+
+<body>
+
+<div id="poll">{% get_polls %}</div>
+
+
+
+</body>
+</html>

poll/templates/poll_answer_ajax.html

+{% load i18n %}
+{% if poll %}
+<p><strong>{% trans "Thank for answering the poll." %}</strong></p>
+<p>{% trans "Here are the current results:" %}</p> 
+{% for a in poll.get_answers_stat %}
+<p>{{a.1}} ({{a.2}}) <br /><div style="background-color:#7db6f0; height:10px; width:{{a.3}}px;">&nbsp;</div></p>
+
+{% endfor %}
+{% else %}
+<p>{% trans "This poll is unpublished and can not be answered." %}</p>
+{% endif %}                   

poll/templates/polls.html

+{% load i18n %}
+{% if polls %}
+{% for p in polls %}
+<div id="form-{{p.id}}">
+<p><strong>{{p.question}}</strong></p>
+<div class="error_field"></div>
+<form> 
+	{% csrf_token %}
+	{% for a in p.get_answers %}
+	<p><input type="radio" name="answer" value="{{a.0}}"> {{a.1}}</p>
+	{% endfor %}
+	<a class="submit" href="#{{p.id}}" id="submit-{{p.id}}"><span>Submit</span></a>
+</form>
+</div>
+<div class="clear">&nbsp;</div>
+{% endfor %}
+<script>
+	// AJAX poll submission    
+	$(function() {
+
+		
+		$('#poll a.submit').click(function(){
+		 var poll_id = $(this).attr('id');
+		 var poll_id = poll_id.replace('submit-','')
+         //answer_id = $('#form-'+poll_id+' form input[type="radio"]:selected').val();
+		 var answer_id = $('#form-'+poll_id+" input[@name='answer']:checked").val();
+		 var form_data = false;
+		if(typeof answer_id != 'undefined'){
+		   post_url = "/poll/submit/" + poll_id+'/'+answer_id;
+            $('#form-'+poll_id).slideUp('fast', function(){  
+				//$('#latest_work .projects').css('background-image','url('+SITE_URL+'system/pyrocms/themes/vivaaspire/img/loading.gif)');
+				//send the request to the server
+				$.post(post_url, form_data, function(data, response, xhr) {
+					//$('#latest_work .projects').css('background-image','none');
+					$('#form-'+poll_id).html(data).slideDown('fast',function(){}); 
+                });
+				
+			});  
+		}  
+		else{
+		   $('#form-'+poll_id+ ' .error_field').html('<p class="error">{% trans "Please choose an answer" %}</p>'); 
+		}
+		  
+	})  
+		
+	}); 
+</script>
+{% else %}
+<p>{% trans "There are no polls published." %}
+{% endif %}
+                   
Add a comment to this file

poll/templatetags/.DS_Store

Binary file added.

Add a comment to this file

poll/templatetags/__init__.py

Empty file added.

Add a comment to this file

poll/templatetags/__init__.pyc

Binary file added.

poll/templatetags/poll_tags.py

+from django.template import Library, Node, resolve_variable, TemplateSyntaxError
+from gpoll.poll.models import *		 
+from django.template import RequestContext
+register = Library()
+import datetime
+now = datetime.datetime.now()
+today = datetime.date(year=now.year, month=now.month, day=now.day) 
+
+
+@register.inclusion_tag("polls.html")
+def get_polls(limit=2):
+	polls = poll.objects.filter(publish=1,	publish_date__lte=today).order_by('-publish_date')[:limit]
+	return {"polls":polls}
Add a comment to this file

poll/templatetags/poll_tags.pyc

Binary file added.

+"""
+This file demonstrates writing tests using the unittest module. These will pass
+when you run "manage.py test".
+
+Replace this with more appropriate tests for your application.
+"""
+
+from django.test import TestCase
+
+
+class SimpleTest(TestCase):
+    def test_basic_addition(self):
+        """
+        Tests that 1 + 1 always equals 2.
+        """
+        self.assertEqual(1 + 1, 2)
+from django.conf.urls.defaults import * 
+urlpatterns = patterns('gpoll', 
+    url(r'^/?$', 'poll.views.default', name='default'),
+    url(r'^submit/(?P<poll_id>[-\d]+)/(?P<answer_id>[-\d]+)/?$', 'poll.views.submit', name='poll-ajax-submit'),
+	#poll export data
+	url(r'^export-data/(?P<object_id>[-\d]+)?$', 'poll.views.export_answers', name="poll_export_answers"),
+)                  

Binary file added.

+from django.http import HttpResponse, HttpRequest, HttpResponseRedirect, Http404
+from django.shortcuts import render_to_response, get_object_or_404
+from gpoll.settings import MEDIA_ROOT
+from gpoll.poll.models import *		
+from django.contrib.auth.decorators import login_required
+from django.template import RequestContext
+#Import the necessary libraries 
+import csv, codecs, cStringIO, sys, os
+class UnicodeWriter:
+	
+	"""
+	A CSV writer which will write rows to CSV file "f",
+	which is encoded in the given encoding.
+	"""
+
+	def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
+		# Redirect output to a queue
+		self.queue = cStringIO.StringIO()
+		self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
+		self.stream = f
+		self.encoder = codecs.getincrementalencoder(encoding)()
+
+	def writerow(self, row):
+		self.writer.writerow([s.encode("utf-8") for s in row])
+		# Fetch UTF-8 output from the queue ...
+		data = self.queue.getvalue()
+		data = data.decode("utf-8")
+		# ... and reencode it into the target encoding
+		data = self.encoder.encode(data)
+		# write to the target stream
+		self.stream.write(data)
+		# empty queue
+		self.queue.truncate(0)
+
+	def writerows(self, rows):
+		for row in rows:
+			self.writerow(row)
+
+		
+#Decorator to make sure the user is logged in		
+@login_required
+def export_answers(request, object_id):
+	
+	#get the poll object
+	poll_obj = get_object_or_404(poll, pk=object_id)
+	
+	#Create a file name containing the poll id
+	filename = 'answer_list_%s.csv' % poll_obj.id
+	
+	#DEfine the path to the file to create and render
+	poll_dir = 'poll'
+	path = MEDIA_ROOT+'%s/%s' % (poll_dir, filename)		   
+	
+	#Create the poll folder if it doesn't exist
+	if not os.path.exists(MEDIA_ROOT+poll_dir):
+		os.makedirs(MEDIA_ROOT+poll_dir)
+
+	FILE = open(path, "w")
+	data = poll_submission.objects.filter(poll_ref=poll_obj).order_by('submit_date')
+	
+	FILE = UnicodeWriter(open(path, "w"), delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
+	FILE.writerow([unicode('Poll question'),unicode('Member name'),unicode('Answer id'),unicode('Answer text'),unicode("Submit date")])
+	for item in data:
+		FILE.writerow([unicode(poll_obj.question),unicode(item.member.fullname()),unicode(item.answer_id),unicode(item.answer_text),unicode(item.submit_date)])
+	#FILE.close()
+	FILE = open(path, "r")												  
+	response = HttpResponse(FILE.read(), mimetype='application/csv')
+	response['Content-Disposition'] = 'attachment; filename=%s' % filename
+
+	return response        
+	
+	
+		
+def submit(request, poll_id, answer_id):
+
+	
+	#get the poll object
+	poll_obj = get_object_or_404(poll, pk=poll_id)
+	print poll_obj.get_answers_stat()
+	if poll_obj.published() == 1:
+		answers = poll_obj.get_answers()
+		answer = answers[int(answer_id)-1]
+		poll_submission.objects.create(poll_ref=poll_obj, answer_id=answer[0], answer_text=answer[1])
+	else:
+		poll_obj=False
+	#Assign template for AJAX response
+	template = 'poll_answer_ajax.html'
+	return render_to_response(template, {'poll':poll_obj},
+						   context_instance=RequestContext(request))
+						
+def default(request):
+
+	template = 'default.html'
+	return render_to_response(template, {},
+						   context_instance=RequestContext(request))

Binary file added.

Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.