1. Guillaume Piot
  2. django-ajax-poll


django-ajax-poll / poll / views.py

Guillaume Piot 663d115 

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
		# empty queue

	def writerows(self, rows):
		for row in rows:

#Decorator to make sure the user is logged in		
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):

	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 = 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])
	#Assign template for AJAX response
	template = 'poll_answer_ajax.html'
	return render_to_response(template, {'poll':poll_obj},
def default(request):

	template = 'default.html'
	return render_to_response(template, {},