Skip to content

Instantly share code, notes, and snippets.

@andybak
Created April 27, 2011 16:23
Show Gist options
  • Save andybak/944595 to your computer and use it in GitHub Desktop.
Save andybak/944595 to your computer and use it in GitHub Desktop.
A Python style question
class MultipleChoiceAnswerForm(ModelForm):
class Meta:
model = MultipleChoiceAnswer
fields=('question' ,'answer',)
widgets = {
'question': HiddenInput(),
'answer': RadioSelect(renderer=MyRadioRenderer),
}
def survey(request, key):
try:
respondent = Respondent.objects.get(key=key)
except Respondent.DoesNotExist:
return Http404
if respondent.survey_completed == True:
template = 'message.html'
page = {
'title_default': SURVEY_NAME,
'content': 'Welcome to the %s' % SURVEY_NAME,
}
else:
page = {
'title_default': SURVEY_NAME,
'content': 'Welcome to the %s' % SURVEY_NAME,
}
if request.method == 'POST':
sections = {}
all_valid = True
for section in Section.objects.all():
questions = {}
for question in section.multiplechoicequestion_set.all():
answer = MultipleChoiceAnswer(question = question)
form = MultipleChoiceAnswerForm(request.POST, prefix="Q%s" % question.id, instance = answer)
all_valid &= form.is_valid()
questions[question.question_text] = form
sections[section.name] = questions
if all_valid:
for section in sections.values():
for form in section.values():
answer = MultipleChoiceAnswer(question = form.cleaned_data['question'], answer=form.cleaned_data['answer'], respondent=respondent)
answer.save()
respondent.survey_completed = True
respondent.save()
template = 'message.html'
page['content'] = "Thank-you for completing this survey"
else:
sections = {}
for section in Section.objects.all():
questions = {}
for question in section.multiplechoicequestion_set.all():
answer = MultipleChoiceAnswer(question = question)
form = MultipleChoiceAnswerForm(prefix="Q%s" % question.id, instance = answer)
questions[question.question_text] = form
sections[section.name] = questions
template = 'survey.html'
context = {
'sections': sections,
'page': page,
}
return render_to_response(
template,
context,
RequestContext(request),
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment