2012-02-15 10:46:55 +01:00
|
|
|
from django.http import HttpResponseRedirect
|
2012-02-19 17:31:17 +01:00
|
|
|
from django.forms.models import modelform_factory
|
2012-02-15 10:46:55 +01:00
|
|
|
|
2012-03-06 12:16:03 +01:00
|
|
|
from utils.views import TemplateView
|
|
|
|
|
|
|
|
|
2012-02-15 10:46:55 +01:00
|
|
|
class PollFormView(TemplateView):
|
|
|
|
template_name = 'poll/poll.html'
|
|
|
|
poll_argument = 'poll_id'
|
|
|
|
|
|
|
|
def set_poll(self, poll_id):
|
|
|
|
poll_id = poll_id
|
|
|
|
self.poll = self.poll_class.objects.get(pk=poll_id)
|
|
|
|
|
|
|
|
def get_context_data(self, **kwargs):
|
|
|
|
context = super(PollFormView, self).get_context_data(**kwargs)
|
|
|
|
self.set_poll(self.kwargs['poll_id'])
|
|
|
|
context['poll'] = self.poll
|
2012-02-19 17:31:17 +01:00
|
|
|
if 'forms' in kwargs:
|
|
|
|
context['forms'] = kwargs['forms']
|
|
|
|
context['pollform'] = kwargs['pollform']
|
|
|
|
else:
|
|
|
|
context['forms'] = self.poll.get_vote_forms()
|
|
|
|
FormClass = self.get_modelform_class()
|
|
|
|
context['pollform'] = FormClass(instance=self.poll, prefix='pollform')
|
2012-02-15 10:46:55 +01:00
|
|
|
return context
|
|
|
|
|
|
|
|
def get_success_url(self):
|
|
|
|
return self.success_url
|
|
|
|
|
2012-02-19 17:31:17 +01:00
|
|
|
def get_modelform_class(self):
|
|
|
|
fields = []
|
|
|
|
self.poll.append_pollform_fields(fields)
|
|
|
|
return modelform_factory(self.poll.__class__, fields=fields)
|
|
|
|
|
2012-02-15 10:46:55 +01:00
|
|
|
def post(self, request, *args, **kwargs):
|
2012-02-19 17:31:17 +01:00
|
|
|
self.set_poll(self.kwargs['poll_id'])
|
2012-02-15 10:46:55 +01:00
|
|
|
forms = self.poll.get_vote_forms(data=self.request.POST)
|
2012-02-19 17:31:17 +01:00
|
|
|
|
|
|
|
FormClass = self.get_modelform_class()
|
|
|
|
pollform = FormClass(data=self.request.POST, instance=self.poll, prefix='pollform')
|
|
|
|
|
2012-02-15 10:46:55 +01:00
|
|
|
error = False
|
|
|
|
for form in forms:
|
|
|
|
if not form.is_valid():
|
|
|
|
error = True
|
2012-02-19 17:31:17 +01:00
|
|
|
|
|
|
|
if not pollform.is_valid():
|
|
|
|
error = True
|
|
|
|
|
2012-02-15 10:46:55 +01:00
|
|
|
if error:
|
2012-02-19 17:31:17 +01:00
|
|
|
return self.render_to_response(self.get_context_data(
|
|
|
|
forms=forms,
|
|
|
|
pollform=pollform,
|
|
|
|
))
|
2012-02-15 10:46:55 +01:00
|
|
|
|
|
|
|
for form in forms:
|
|
|
|
data = {}
|
|
|
|
for value in self.poll.vote_values:
|
|
|
|
data[value] = form.cleaned_data[value]
|
|
|
|
self.poll.set_form_values(form.option, data)
|
2012-02-19 17:31:17 +01:00
|
|
|
|
|
|
|
pollform.save()
|
2012-02-15 10:46:55 +01:00
|
|
|
return HttpResponseRedirect(self.get_success_url())
|