From db90300a95d9a78d093d02fcbc684f2d4c6b28d7 Mon Sep 17 00:00:00 2001 From: Ian Ward Date: Sun, 18 Apr 2010 13:20:11 -0400 Subject: [PATCH] fix for Answer.choice_str and modified answer format --- questionnaire/models.py | 21 +++++++++++++++++++-- questionnaire/views.py | 12 +----------- 2 files changed, 20 insertions(+), 13 deletions(-) diff --git a/questionnaire/models.py b/questionnaire/models.py index 342e0f6..df8734b 100644 --- a/questionnaire/models.py +++ b/questionnaire/models.py @@ -322,13 +322,30 @@ class Answer(models.Model): def choice_str(self, secondary = False): choice_string = "" choices = self.question.get_choices() - split_answers = self.answer.split() for choice in choices: - for split_answer in split_answers: + for split_answer in self.split_answer(): if str(split_answer) == choice.value: choice_string += str(choice.text) + " " + def split_answer(self): + """ + Decode stored answer value and return as a list of choices. + Any freeform value will be returned in a list as the last item. + + Calling code should be tolerant of freeform answers outside + of additional [] if data has been stored in plain text format + """ + try: + return json.loads(self.answer) + except ValueError: + # this was likely saved as plain text, try to guess what the + # value(s) were + if 'multiple' in self.question.type: + return self.answer.split('; ') + else: + return [self.answer] + def check_answer(self): "Confirm that the supplied answer matches what we expect" return True diff --git a/questionnaire/views.py b/questionnaire/views.py index 55bfaf2..fd13045 100644 --- a/questionnaire/views.py +++ b/questionnaire/views.py @@ -479,17 +479,7 @@ def export_csv(request, qid): # questionnaire_id row = ["--"] * len(columns) row[0] = "%s/%s" % (subject.id, subject.state) row[1] = runid - try: - ans = loads(answer.answer) - except ValueError: - # this was likely saved as plain text, try to guess what the - # value(s) were - if 'multiple' in answer.question.type: - ans = answer.answer.split('; ') - else: - # code below is tolerant of freeform answers outside of - # additional [], as they would be saved in json format - ans = [answer.answer] + ans = answer.split_answer() for choice in ans: col = None if type(choice) == list: