예제 #1
0
 def test_answer_value_methods(self):
     value = 'me doing somthing'
     test_answer1 = 'nothing good'
     self.assertFalse(Answer.equals(test_answer1, value))
     self.assertTrue(Answer.equals(value, value))
     self.assertTrue(Answer.starts_with(value, 'me d'))
     self.assertFalse(Answer.ends_with(value, 'no thing'))
     self.assertTrue(Answer.ends_with(value, 'somthing'))
     self.assertFalse(Answer.greater_than(5, 9))
     self.assertTrue(Answer.greater_than(9, 5))
     self.assertTrue(Answer.less_than(5, 9))
     self.assertFalse(Answer.less_than(9, 5))
     self.assertFalse(Answer.between(9, 5, 7))
     self.assertTrue(Answer.between(9, 5, 11))
     self.assertTrue(Answer.passes_test('17 > 10'))
     self.assertFalse(NumericalAnswer.greater_than(5, 9))
     self.assertTrue(NumericalAnswer.greater_than(9, 5))
     self.assertTrue(NumericalAnswer.less_than(5, 9))
     self.assertFalse(NumericalAnswer.less_than(9, 5))
     self.assertFalse(NumericalAnswer.between(9, 5, 7))
     self.assertTrue(NumericalAnswer.between(9, 5, 11))
     self.assertFalse(TextAnswer.equals(test_answer1, value))
     self.assertTrue(TextAnswer.equals(value, value))
     self.assertFalse(MultiChoiceAnswer.equals(test_answer1, value))
     self.assertTrue(MultiChoiceAnswer.equals(value, value))
     self.assertFalse(MultiSelectAnswer.equals(test_answer1, value))
     self.assertTrue(MultiSelectAnswer.equals(value, value))
     self.assertFalse(DateAnswer.greater_than('12-09-2017', '12-09-2017'))
     self.assertTrue(DateAnswer.greater_than('13-09-2017', '12-09-2017'))
     self.assertFalse(DateAnswer.less_than('18-09-2017', '12-09-2017'))
     self.assertTrue(DateAnswer.less_than('13-09-2017', '17-09-2017'))
     self.assertFalse(
         DateAnswer.between('18-09-2017', '12-09-2017', '16-09-2017'))
     self.assertTrue(
         DateAnswer.between('14-09-2017', '12-09-2017', '16-09-2017'))
예제 #2
0
    def _check__multichoice_and_options_compatibility(self, answer_type, options):
        if answer_type in [MultiChoiceAnswer.choice_name(), MultiSelectAnswer.choice_name()] and not options:
            message = 'Question Options missing.'
            self._errors['answer_type'] = self.error_class([message])
            del self.cleaned_data['answer_type']

        if answer_type not in [MultiChoiceAnswer.choice_name(), MultiSelectAnswer.choice_name()] and options:
            del self.cleaned_data['options']
예제 #3
0
    def _check__multichoice_and_options_compatibility(self, answer_type, options):
        if answer_type in [MultiChoiceAnswer.choice_name(), MultiSelectAnswer.choice_name()] and not options:
            message = 'Question Options missing.'
            self._errors['answer_type'] = self.error_class([message])
            del self.cleaned_data['answer_type']

        if answer_type not in [MultiChoiceAnswer.choice_name(), MultiSelectAnswer.choice_name()] and options:
            del self.cleaned_data['options']
예제 #4
0
 def save(self, *args, **kwargs):
     next_question = None
     desc = self._make_desc()
     if self.cleaned_data['action'] in [
             self.ASK_SUBQUESTION, self.SKIP_TO, self.BACK_TO]:
         next_question = Question.get(pk=self.cleaned_data['next_question'])
     if self.cleaned_data['action'] == self.REANSWER:
         next_question = self.question
     validation = ResponseValidation.objects.create(validation_test=self.cleaned_data['condition'])
     flow = QuestionFlow.objects.create(question=self.question,
                                        validation=validation,
                                        next_question=next_question,
                                        desc=desc)
     if self.cleaned_data['action'] == self.ASK_SUBQUESTION:
         # connect back to next inline question of the main
         QuestionFlow.objects.create(
             question=next_question,
             desc=desc,
             next_question=self.batch.next_inline(
                 self.question))
     if self.cleaned_data['condition'] == 'between':
         TextArgument.objects.create(validation=validation, position=0, param=self.cleaned_data['min_value'])
         TextArgument.objects.create(validation=validation, position=1, param=self.cleaned_data['max_value'])
     else:
         value = self.cleaned_data.get('value', '')
         if self.question.answer_type in [
                 MultiChoiceAnswer.choice_name(),
                 MultiSelectAnswer.choice_name()]:
             value = self.cleaned_data['option']
         TextArgument.objects.create(validation=validation, position=0, param=value)
     # clean up now, remove all zombie questions
     self.question.qset.zombie_questions().delete()
 def test_logic_form_does_not_have_options_for_non_multi_type_questions(self):
     answer_types = Answer.answer_types()
     for answer_type in answer_types:
         if answer_type not in [MultiSelectAnswer.choice_name(), MultiChoiceAnswer.choice_name()]:                
             q = Question.objects.create(identifier=answer_type, text="text", answer_type=answer_type,
                                             qset_id=self.qset.id, response_validation_id=1)
             l = LogicForm(q)
             self.assertFalse(l.fields.get('option'))
예제 #6
0
 def test_other_answer_methods(self):
     interviews = self._prep_answers()
     m_answer = MultiChoiceAnswer.objects.last()
     self.assertEqual(m_answer.pretty_print(as_label=False),
                      m_answer.value.text)
     self.assertEqual(m_answer.pretty_print(as_label=True),
                      m_answer.value.order)
     multiselect_question = Question.objects.filter(
         answer_type=MultiSelectAnswer.choice_name()).last()
     MultiSelectAnswer.create(self.interview, multiselect_question, 'Y N')
     self.assertEqual(MultiSelectAnswer.objects.count(), 1)
     multiselect = MultiSelectAnswer.objects.last()
     self.assertEqual(multiselect.to_text(), ' and '.join(['Y', 'N']))
     self.assertEqual(multiselect.to_label(), ' and '.join(['1', '2']))
     self.assertEqual(multiselect.pretty_print(as_label=False),
                      multiselect.to_text())
     self.assertEqual(multiselect.pretty_print(as_label=True),
                      multiselect.to_label())
예제 #7
0
 def test_update_multiselect_answer(self):
     qset = self.qset
     self._create_test_non_group_questions(qset)
     multiselect_question = Question.objects.filter(answer_type=MultiSelectAnswer.choice_name()).first()
     options = multiselect_question.options.all()
     raw_answer = ' '.join([options.first().text, options.last().text])
     MultiSelectAnswer.create(self.interview, multiselect_question, raw_answer)
     self.assertEquals(MultiSelectAnswer.objects.count(), 1)
     multichoice_answer = MultiSelectAnswer.objects.first()
     self.assertEquals(multichoice_answer.as_text, raw_answer)
     self.assertEquals(multichoice_answer.as_value, raw_answer)
     # not save all options as queryset
     MultiSelectAnswer.create(self.interview, multiselect_question, multiselect_question.options.all())
     self.assertEquals(MultiSelectAnswer.objects.count(), 2)
     multichoice_answer = MultiSelectAnswer.objects.last()
     self.assertEquals(multichoice_answer.as_text,
                       ' '.join(multiselect_question.options.values_list('text', flat=True)))
     self.assertEquals(multichoice_answer.as_value,
                       ' '.join(multiselect_question.options.values_list('text', flat=True)))
예제 #8
0
 def __init__(self, *args, **kwargs):
     super(AnswerForm, self).__init__(*args, **kwargs)
     # self.fields['uid'] = forms.CharField(initial=access.user_identifier, widget=forms.HiddenInput)
     if question.answer_type == DateAnswer.choice_name():
         self.fields['value'] = forms.DateField(
             label='Answer',
             input_formats=[
                 settings.DATE_FORMAT,
             ],
             widget=forms.DateInput(attrs={
                 'placeholder': 'Answer',
                 'class': 'datepicker'
             },
                                    format=settings.DATE_FORMAT))
     if question.answer_type == GeopointAnswer.choice_name():
         model_field = get_form_field_no_validation(forms.CharField)
         self.fields['value'] = model_field(
             label='Answer',
             widget=forms.TextInput(
                 attrs={
                     'placeholder':
                     'Lat[space4]Long[space4'
                     'Altitude[space4]Precision'
                 }))
     if question.answer_type == MultiChoiceAnswer.choice_name():
         self.fields['value'] = forms.ChoiceField(
             choices=[(opt.order, opt.text)
                      for opt in question.options.all()],
             widget=forms.RadioSelect)
         self.fields['value'].empty_label = None
     if access.choice_name() == USSDAccess.choice_name():
         self.fields['value'].widget = forms.NumberInput()
     if question.answer_type == MultiSelectAnswer.choice_name():
         self.fields['value'] = forms.ModelMultipleChoiceField(
             queryset=question.options.all(),
             widget=forms.CheckboxSelectMultiple)
     accept_types = {
         AudioAnswer.choice_name(): 'audio/*',
         VideoAnswer.choice_name(): 'video/*',
         ImageAnswer.choice_name(): 'image/*'
     }
     if question.answer_type in [
             AudioAnswer.choice_name(),
             VideoAnswer.choice_name(),
             ImageAnswer.choice_name()
     ]:
         self.fields['value'].widget.attrs = {
             'accept':
             accept_types.get(question.answer_type,
                              '|'.join(accept_types.values()))
         }
     if access.choice_name() == USSDAccess.choice_name():
         self.fields['value'].label = ''
     else:
         self.fields['value'].label = 'Answer'
예제 #9
0
    def __init__(self, question, initial=None, *args, **kwargs):
        super(LogicForm, self).__init__(initial=initial, *args, **kwargs)
        data = kwargs.get('data', None)
        batch = question.qset
        self.question = question
        self.batch = batch
        self.fields['condition'] = forms.ChoiceField(
            label='Eligibility criteria',
            choices=[],
            widget=forms.Select,
            required=False)
        self.fields['attribute'] = forms.ChoiceField(
            label='Attribute', choices=[
                ('value', 'Value'), ], widget=forms.Select, required=False)
        self.fields['condition'].choices = [
            (validator.__name__,
             validator.__name__.upper()) for validator in Answer.get_class(
                question.answer_type).validators()]
        if question.answer_type in [
                MultiChoiceAnswer.choice_name(),
                MultiSelectAnswer.choice_name()]:
            self.fields['option'] = forms.ChoiceField(
                label='', choices=[], widget=forms.Select, required=True)
            self.fields['option'].choices = [
                (option.text, option.text) for option in question.options.all()]
        else:
            self.fields['value'] = forms.CharField(label='', required=False)
            self.fields['min_value'] = forms.CharField(
                label='', required=False, widget=forms.TextInput(
                    attrs={
                        'placeholder': 'Min Value'}))
            self.fields['max_value'] = forms.CharField(
                label='', required=False, widget=forms.TextInput(
                    attrs={
                        'placeholder': 'Max Value'}))
            if question.answer_type == DateAnswer.choice_name():
                self.fields['value'].widget.attrs['class'] = 'datepicker'
                self.fields['min_value'].widget.attrs['class'] = 'datepicker'
                self.fields['max_value'].widget.attrs['class'] = 'datepicker'
            # validate_with_question = forms.ChoiceField(label='', choices=[], widget=forms.Select, required=False)
        self.fields['action'] = forms.ChoiceField(
            label='Then', choices=[], widget=forms.Select, required=True)
        flows = self.question.flows.all()
        [f.next_question.pk for f in flows if f.next_question]
        next_q_choices = [(q.pk, q.text) for q in batch.questions_inline(
        ) if q.pk is not self.question.pk]
        # and q.pk not in existing_nexts]
        next_q_choices.extend([(q.pk, q.text)
                               for q in batch.zombie_questions()])
        self.fields['next_question'] = forms.ChoiceField(
            label='', choices=next_q_choices, widget=forms.Select, required=False)
        #self.fields['next_question'].widget.attrs['class'] = 'chzn-select'
        self.fields['action'].choices = self.ACTIONS.items()

        data.get('action', None) if data else None
예제 #10
0
 def _create_test_non_group_questions(self, qset):
     # Basically create questions for this question set which is not having groups
     self._create_ussd_non_group_questions(qset)
     # Multiselect questions
     data = {
         'answer_type': MultiSelectAnswer.choice_name(),
         'text': 'multi select answer text',
         'identifier':
         'multi2_select_identifier_%s' % random.randint(1, 100),
         'qset': qset.id,
         'options': ['Y', 'N', 'MB']
     }
     self._save_question(qset, data)
     # Date answer
     data = {
         'answer_type': DateAnswer.choice_name(),
         'text': 'date answer text',
         'identifier': 'date2_identifier_%s' % random.randint(1, 100),
         'qset': qset.id,
     }
     self._save_question(qset, data)
     # Geopoint answer
     data = {
         'answer_type': GeopointAnswer.choice_name(),
         'text': 'geo point text',
         'identifier': 'geo2_identifier_%s' % random.randint(1, 100),
         'qset': qset.id
     }
     self._save_question(qset, data)
     # Image answer
     data = {
         'answer_type': ImageAnswer.choice_name(),
         'text': 'image answer text',
         'identifier': 'image2_identifier_%s' % random.randint(1, 100),
         'qset': qset.id
     }
     self._save_question(qset, data)
     # Audio answer
     data = {
         'answer_type': AudioAnswer.choice_name(),
         'text': 'audio answer text',
         'identifier': 'audio2_identifier_%s' % random.randint(1, 100),
         'qset': qset.id
     }
     self._save_question(qset, data)
     # Video answer
     data = {
         'answer_type': VideoAnswer.choice_name(),
         'text': 'video answer text',
         'identifier': 'video2_identifier_%s' % random.randint(1, 100),
         'qset': qset.id
     }
     self._save_question(qset, data)
     self.qset.refresh_from_db()
 def test_logic_form_has_options_for_multi_type_questions(self):
     for answer_type in [
             MultiSelectAnswer.choice_name(),
             MultiChoiceAnswer.choice_name()
     ]:
         q = Question.objects.create(identifier=answer_type,
                                     text="text",
                                     answer_type=answer_type,
                                     qset_id=self.qset.id,
                                     response_validation_id=1)
         l = LogicForm(q)
         self.assertTrue(l.fields.get('option'))
예제 #12
0
    def clean_value(self):

        if self.question.answer_type not in [
                MultiSelectAnswer.choice_name(),
                MultiChoiceAnswer.choice_name()] and self.cleaned_data['condition'] != 'between' and len(
                self.cleaned_data['value'].strip()) == 0:
            raise ValidationError("Field is required.")
        value = self.cleaned_data.get('value', '')
        if value:
            Answer.get_class(
                self.question.answer_type).validate_test_value(value)
        return self.cleaned_data.get('value', '')
예제 #13
0
 def _create_test_non_group_questions(self, qset):
     # Basically create questions for this question set which is not having groups
     self._create_ussd_non_group_questions(qset)
     # Multiselect questions
     data = {
         'answer_type': MultiSelectAnswer.choice_name(),
         'text': 'multi select answer text',
         'identifier': 'multi2_select_identifier_%s' % random.randint(1, 100),
         'qset': qset.id,
         'options': ['Y', 'N', 'MB']
     }
     self._save_question(qset, data)
     # Date answer
     data = {
         'answer_type': DateAnswer.choice_name(),
         'text': 'date answer text',
         'identifier': 'date2_identifier_%s' % random.randint(1, 100),
         'qset': qset.id,
     }
     self._save_question(qset, data)
     # Geopoint answer
     data = {
         'answer_type': GeopointAnswer.choice_name(),
         'text': 'geo point text',
         'identifier': 'geo2_identifier_%s' % random.randint(1, 100),
         'qset': qset.id
     }
     self._save_question(qset, data)
     # Image answer
     data = {
         'answer_type': ImageAnswer.choice_name(),
         'text': 'image answer text',
         'identifier': 'image2_identifier_%s' % random.randint(1, 100),
         'qset': qset.id
     }
     self._save_question(qset, data)
     # Audio answer
     data = {
         'answer_type': AudioAnswer.choice_name(),
         'text': 'audio answer text',
         'identifier': 'audio2_identifier_%s' % random.randint(1, 100),
         'qset': qset.id
     }
     self._save_question(qset, data)
     # Video answer
     data = {
         'answer_type': VideoAnswer.choice_name(),
         'text': 'video answer text',
         'identifier': 'video2_identifier_%s' % random.randint(1, 100),
         'qset': qset.id
     }
     self._save_question(qset, data)
     self.qset.refresh_from_db()
예제 #14
0
    def clean_value(self):

        if self.question.answer_type not in [
                MultiSelectAnswer.choice_name(),
                MultiChoiceAnswer.choice_name()
        ] and self.cleaned_data['condition'] != 'between' and len(
                self.cleaned_data['value'].strip()) == 0:
            raise ValidationError("Field is required.")
        value = self.cleaned_data.get('value', '')
        if value:
            Answer.get_class(
                self.question.answer_type).validate_test_value(value)
        return self.cleaned_data.get('value', '')
예제 #15
0
    def clean_value(self):

        if self.question.answer_type not in  [MultiSelectAnswer.choice_name(), MultiChoiceAnswer.choice_name()] \
                            and self.cleaned_data['condition'] != 'between' and len(self.cleaned_data['value'].strip()) == 0:
            raise ValidationError("Field is required.")
        value = self.cleaned_data.get('value', '')
        if value:
            #now check if value is valid answer type
            try:
                Answer.get_class(self.question.answer_type)(self.question, value)
            except:
                raise ValidationError("Invalid value.")
        return self.cleaned_data.get('value', '')
예제 #16
0
    def clean_value(self):

        if self.question.answer_type not in  [MultiSelectAnswer.choice_name(), MultiChoiceAnswer.choice_name()] \
                            and self.cleaned_data['condition'] != 'between' and len(self.cleaned_data['value'].strip()) == 0:
            raise ValidationError("Field is required.")
        value = self.cleaned_data.get('value', '')
        if value:
            #now check if value is valid answer type
            try:
                Answer.get_class(self.question.answer_type)(self.question,
                                                            value)
            except:
                raise ValidationError("Invalid value.")
        return self.cleaned_data.get('value', '')
 def get_summarised_answers(self):
     data = []
     q_opts = {}
     if self.specific_households is None:
         all_households = Household.objects.filter(
             listing__survey_houselistings__survey=self.survey)
     else:
         all_households = Household.objects.filter(
             pk__in=self.specific_households,
             listing__survey_houselistings__survey=self.survey)
     locations = list(
         set(all_households.values_list('listing__ea__locations',
                                        flat=True)))
     for location_id in locations:
         households_in_location = all_households.filter(
             listing__ea__locations=location_id)
         household_location = Location.objects.get(id=location_id)
         location_ancestors = household_location.get_ancestors(include_self=True).\
             exclude(parent__isnull='country').values_list('name', flat=True)
         answers = []
         for household in households_in_location:
             for member in household.members.all():
                 try:
                     answers = list(location_ancestors)
                     member_gender = 'Male' if member.gender == HouseholdMember.MALE else 'Female'
                     answers.extend([
                         household.listing.ea.name, household.house_number,
                         '%s-%s' % (member.surname, member.first_name),
                         str(member.age),
                         member.date_of_birth.strftime(
                             settings.DATE_FORMAT), member_gender
                     ])
                     for question in self.questions:
                         reply = member.reply(question)
                         if question.answer_type in [MultiChoiceAnswer.choice_name(),
                                                     MultiSelectAnswer.choice_name()]\
                                 and self.multi_display == self.AS_LABEL:
                             label = q_opts.get((question.pk, reply), None)
                             if label is None:
                                 try:
                                     label = question.options.get(
                                         text__iexact=reply).order
                                 except QuestionOption.DoesNotExist:
                                     label = reply
                                 q_opts[(question.pk, reply)] = label
                             reply = str(label)
                         answers.append(reply.encode('utf8'))
                     data.append(answers)
                 except Exception, ex:
                     print 'Error ', str(ex)
 def test_logic_form_does_not_have_options_for_non_multi_type_questions(
         self):
     answer_types = Answer.answer_types()
     for answer_type in answer_types:
         if answer_type not in [
                 MultiSelectAnswer.choice_name(),
                 MultiChoiceAnswer.choice_name()
         ]:
             q = Question.objects.create(identifier=answer_type,
                                         text="text",
                                         answer_type=answer_type,
                                         qset_id=self.qset.id,
                                         response_validation_id=1)
             l = LogicForm(q)
             self.assertFalse(l.fields.get('option'))
 def test_update_multiselect_answer(self):
     qset = self.qset
     self._create_test_non_group_questions(qset)
     multiselect_question = Question.objects.filter(
         answer_type=MultiSelectAnswer.choice_name()).first()
     options = multiselect_question.options.all()
     raw_answer = ' '.join([options.first().text, options.last().text])
     MultiSelectAnswer.create(self.interview, multiselect_question,
                              raw_answer)
     self.assertEquals(MultiSelectAnswer.objects.count(), 1)
     multichoice_answer = MultiSelectAnswer.objects.first()
     self.assertEquals(multichoice_answer.as_text, raw_answer)
     self.assertEquals(multichoice_answer.as_value, raw_answer)
     # not save all options as queryset
     MultiSelectAnswer.create(self.interview, multiselect_question,
                              multiselect_question.options.all())
     self.assertEquals(MultiSelectAnswer.objects.count(), 2)
     multichoice_answer = MultiSelectAnswer.objects.last()
     self.assertEquals(
         multichoice_answer.as_text, ' '.join(
             multiselect_question.options.values_list('text', flat=True)))
     self.assertEquals(
         multichoice_answer.as_value, ' '.join(
             multiselect_question.options.values_list('text', flat=True)))
예제 #20
0
 def __init__(self, *args, **kwargs):
     super(AnswerForm, self).__init__(*args, **kwargs)
     # self.fields['uid'] = forms.CharField(initial=access.user_identifier, widget=forms.HiddenInput)
     if question.answer_type == DateAnswer.choice_name():
         self.fields['value'] = forms.DateField(
             label='Answer',
             input_formats=[
                 settings.DATE_FORMAT,
             ],
             widget=forms.DateInput(
                 attrs={
                     'placeholder': 'Answer',
                     'class': 'datepicker'},
                 format=settings.DATE_FORMAT))
     if question.answer_type == GeopointAnswer.choice_name():
         model_field = get_form_field_no_validation(forms.CharField)
         self.fields['value'] = model_field(label='Answer', widget=forms.TextInput(
             attrs={'placeholder': 'Lat[space4]Long[space4' 'Altitude[space4]Precision'}))
     if question.answer_type == MultiChoiceAnswer.choice_name():
         self.fields['value'] = forms.ChoiceField(choices=[(opt.order, opt.text) for opt
                                                           in question.options.all()], widget=forms.RadioSelect)
         self.fields['value'].empty_label = None
     if access.choice_name() == USSDAccess.choice_name():
         self.fields['value'].widget = forms.NumberInput()
     if question.answer_type == MultiSelectAnswer.choice_name():
         self.fields['value'] = forms.ModelMultipleChoiceField(
             queryset=question.options.all(), widget=forms.CheckboxSelectMultiple)
     accept_types = {AudioAnswer.choice_name(): 'audio/*',
                     VideoAnswer.choice_name(): 'video/*',
                     ImageAnswer.choice_name(): 'image/*'
                     }
     if question.answer_type in [
             AudioAnswer.choice_name(),
             VideoAnswer.choice_name(),
             ImageAnswer.choice_name()]:
         self.fields['value'].widget.attrs = {
             'accept': accept_types.get(
                 question.answer_type, '|'.join(
                     accept_types.values()))}
     if access.choice_name() == USSDAccess.choice_name():
         self.fields['value'].label = ''
     else:
         self.fields['value'].label = 'Answer'
예제 #21
0
 def save(self, *args, **kwargs):
     next_question = None
     desc = self._make_desc()
     if self.cleaned_data['action'] in [
             self.ASK_SUBQUESTION, self.SKIP_TO, self.BACK_TO
     ]:
         next_question = Question.get(pk=self.cleaned_data['next_question'])
     if self.cleaned_data['action'] == self.REANSWER:
         next_question = self.question
     validation = ResponseValidation.objects.create(
         validation_test=self.cleaned_data['condition'])
     flow = QuestionFlow.objects.create(question=self.question,
                                        validation=validation,
                                        next_question=next_question,
                                        desc=desc)
     if self.cleaned_data['action'] == self.ASK_SUBQUESTION:
         # connect back to next inline question of the main
         QuestionFlow.objects.create(question=next_question,
                                     desc=desc,
                                     next_question=self.batch.next_inline(
                                         self.question))
     if self.cleaned_data['condition'] == 'between':
         TextArgument.objects.create(validation=validation,
                                     position=0,
                                     param=self.cleaned_data['min_value'])
         TextArgument.objects.create(validation=validation,
                                     position=1,
                                     param=self.cleaned_data['max_value'])
     else:
         value = self.cleaned_data.get('value', '')
         if self.question.answer_type in [
                 MultiChoiceAnswer.choice_name(),
                 MultiSelectAnswer.choice_name()
         ]:
             value = self.cleaned_data['option']
         TextArgument.objects.create(validation=validation,
                                     position=0,
                                     param=value)
     # clean up now, remove all zombie questions
     self.question.qset.zombie_questions().delete()
 def test_answer_validators(self):
     validators = [  # supported validators
         'starts_with',
         'ends_with',
         'equals',
         'between',
         'less_than',
         'greater_than',
         'contains',
     ]
     for func in Answer.validators():
         self.assertIn(func.__name__, validators)
     # test Numeric Answer Validators
     validators = [  # supported validators
         'equals',
         'between',
         'less_than',
         'greater_than',
     ]
     for func in NumericalAnswer.validators():
         self.assertIn(func.__name__, validators)
     # test Text Answer Validators
     validators = [  # supported validators
         'starts_with',
         'ends_with',
         'equals',
         'contains',
     ]
     for func in TextAnswer.validators():
         self.assertIn(func.__name__, validators)
     # Multichoice
     validators = [  # supported validators
         'equals',
     ]
     for func in MultiChoiceAnswer.validators():
         self.assertIn(func.__name__, validators)
     # test Multiselect Answer Validators
     validators = [  # supported validators
         'equals',
         'contains',
     ]
     for func in MultiSelectAnswer.validators():
         self.assertIn(func.__name__, validators)
     # test Date Answer Validators
     validators = [  # supported validators
         'equals',
         'between',
         'less_than',
         'greater_than',
     ]
     for func in DateAnswer.validators():
         self.assertIn(func.__name__, validators)
     # GeoPoint Answer
     validators = [  # supported validators
         'equals',
     ]
     for func in GeopointAnswer.validators():
         self.assertIn(func.__name__, validators)
     # file answers should return no validators
     for answer_class in [VideoAnswer, AudioAnswer, ImageAnswer]:
         self.assertEquals(len(answer_class.validators()), 0)
    def get_interview_answers(self):
        report = []
        member_reports = OrderedDict()
        val_list_args = [
            'interview__ea__locations__name',
            'interview__ea__name',
            'interview__householdmember__household__house_number',
            'interview__householdmember__surname',
            'interview__householdmember__first_name',
            'interview__householdmember__date_of_birth',
            'interview__householdmember__gender',
        ]
        parent_loc = 'interview__ea__locations'
        for i in range(LocationType.objects.count() - 2):
            parent_loc = '%s__parent' % parent_loc
            val_list_args.insert(0, '%s__name' % parent_loc)
        filter_args = {}
        if self.locations:
            filter_args['interview__ea__locations__in'] = self.locations
        if self.specific_households:
            filter_args[
                'interview__householdmember__household__in'] = self.specific_households
        for answer_type in Answer.answer_types():
            query_args = list(val_list_args)
            value = 'value'
            if answer_type in [
                    MultiChoiceAnswer.choice_name(),
                    MultiSelectAnswer.choice_name()
            ]:
                value = 'value__text'
                if self.multi_display == self.AS_LABEL:
                    value = 'value__order'
            query_args.append(value)
            answer_class = Answer.get_class(answer_type)
            # print 'using query_args ', query_args
            answer_data = answer_class.objects.filter(interview__batch=self.batch, **filter_args).\
                values_list('interview__householdmember__pk', 'question__pk', *query_args).\
                        order_by('interview__ea__locations', 'interview__ea',
                                 'interview__householdmember__household', 'interview__householdmember__pk',
                                 'pk', 'loop_id')
            # .distinct(
            #                         'interview__ea__locations',
            #                         'interview__ea',
            #                         'interview__householdmember__household',
            #                         #'interview__householdmember__pk',
            #                         #'question__pk'
            #                        )

            answer_data = list(answer_data)
            # print 'answer data ', len(answer_data)
            #now grab member reports
            for data in answer_data:
                hm_pk, question_pk = data[:2]
                report_data = list(data[2:])
                hm_data = member_reports.get(hm_pk, None)
                if hm_data is None:
                    report_data.insert(
                        -3,
                        str(
                            dateutils.relativedelta(datetime.utcnow().date(),
                                                    report_data[-3]).years))
                    report_data[-3] = report_data[-3].strftime(
                        settings.DATE_FORMAT)
                    report_data[-2] = 'M' if report_data[-2] else 'F'
                    member_details = [
                        unicode(md).encode('utf8') for md in report_data[:-1]
                    ]
                    hm_data = OrderedDict([
                        ('mem_details', member_details),
                    ])
                hm_question_data = hm_data.get(question_pk, [])
                hm_question_data.append(
                    unicode(report_data[-1]).encode('utf8'))
                hm_data[question_pk] = hm_question_data
                member_reports[hm_pk] = hm_data

        for hm in member_reports.values():
            answers = hm.pop('mem_details', [])
            #for question_pk, response_data in hm.items():
            loop_starters = self.batch.loop_starters()
            loop_enders = self.batch.loop_enders()
            started = False
            dept = 0
            for question in self.questions:
                # loop_extras = []
                # boundary = question.loop_boundary()
                # if question in loop_starters:
                #     loop_extras = []
                #     loop_questions = self.batch.loop_backs_questions()[boundary]
                #     for i in range(1, settings.LOOP_QUESTION_REPORT_DEPT):
                #         for q in loop_questions:
                #             question_responses = hm.get(question.pk, [])
                #             if len(question_responses) > i:
                #                 resp = question_responses[i]
                #             else:
                #                 resp = ''
                #             loop_extras.append(resp)
                #     import pdb; pdb.set_trace()
                # if question in loop_enders:
                #     answers.extend(loop_extras)
                answers.append(' > '.join(hm.get(question.pk, [
                    '',
                ])))
            report.append(answers)
        return report
예제 #24
0
 def test_answer_validators(self):
     validators = [                  # supported validators
         'starts_with',
         'ends_with',
         'equals',
         'between',
         'less_than',
         'greater_than',
         'contains',
     ]
     for func in Answer.validators():
         self.assertIn(func.__name__, validators)
     # test Numeric Answer Validators
     validators = [                  # supported validators
         'equals',
         'between',
         'less_than',
         'greater_than',
     ]
     for func in NumericalAnswer.validators():
         self.assertIn(func.__name__, validators)
     # test Text Answer Validators
     validators = [                  # supported validators
         'starts_with',
         'ends_with',
         'equals',
         'contains',
     ]
     for func in TextAnswer.validators():
         self.assertIn(func.__name__, validators)
     # Multichoice
     validators = [                  # supported validators
         'equals',
     ]
     for func in MultiChoiceAnswer.validators():
         self.assertIn(func.__name__, validators)
     # test Multiselect Answer Validators
     validators = [                  # supported validators
         'equals',
         'contains',
     ]
     for func in MultiSelectAnswer.validators():
         self.assertIn(func.__name__, validators)
     # test Date Answer Validators
     validators = [                  # supported validators
         'equals',
         'between',
         'less_than',
         'greater_than',
     ]
     for func in DateAnswer.validators():
         self.assertIn(func.__name__, validators)
     # GeoPoint Answer
     validators = [  # supported validators
         'equals',
     ]
     for func in GeopointAnswer.validators():
         self.assertIn(func.__name__, validators)
     # file answers should return no validators
     for answer_class in [VideoAnswer, AudioAnswer, ImageAnswer]:
         self.assertEquals(len(answer_class.validators()), 0)
예제 #25
0
    def __init__(self, initial=None, question=None, *args, **kwargs):
        super(LogicForm, self).__init__(initial=initial, *args, **kwargs)
        data = kwargs.get('data', None)
        batch = question.batch
        self.question = question
        self.batch = batch
        self.fields['condition'] = forms.ChoiceField(
            label='Eligibility criteria',
            choices=[],
            widget=forms.Select,
            required=False)
        self.fields['attribute'] = forms.ChoiceField(label='Attribute',
                                                     choices=[
                                                         ('value', 'Value'),
                                                     ],
                                                     widget=forms.Select,
                                                     required=False)
        self.fields['condition'].choices = [(validator.__name__, validator.__name__.upper()) \
                                           for validator in Answer.get_class(question.answer_type).validators()]
        if question.answer_type in [
                MultiChoiceAnswer.choice_name(),
                MultiSelectAnswer.choice_name()
        ]:
            self.fields['option'] = forms.ChoiceField(label='',
                                                      choices=[],
                                                      widget=forms.Select,
                                                      required=True)
            self.fields['option'].choices = [
                (option.order, option.text)
                for option in question.options.all()
            ]
        else:
            self.fields['value'] = forms.CharField(label='', required=False)
            self.fields['min_value'] = forms.CharField(
                label='',
                required=False,
                widget=forms.TextInput(attrs={'placeholder': 'Min Value'}))
            self.fields['max_value'] = forms.CharField(
                label='',
                required=False,
                widget=forms.TextInput(attrs={'placeholder': 'Max Value'}))
            if question.answer_type == DateAnswer.choice_name():
                self.fields['value'].widget.attrs['class'] = 'datepicker'
                self.fields['min_value'].widget.attrs['class'] = 'datepicker'
                self.fields['max_value'].widget.attrs['class'] = 'datepicker'
            # validate_with_question = forms.ChoiceField(label='', choices=[], widget=forms.Select, required=False)
        self.fields['action'] = forms.ChoiceField(label='Then',
                                                  choices=[],
                                                  widget=forms.Select,
                                                  required=True)
        flows = self.question.flows.all()
        existing_nexts = [f.next_question.pk for f in flows if f.next_question]
        next_q_choices = [(q.pk, q.text) for q in batch.questions_inline()
                          if q.pk is not self.question.pk]
        # and q.pk not in existing_nexts]
        next_q_choices.extend([(q.pk, q.text)
                               for q in batch.zombie_questions()])
        self.fields['next_question'] = forms.ChoiceField(
            label='',
            choices=next_q_choices,
            widget=forms.Select,
            required=False)
        self.fields['next_question'].widget.attrs['class'] = 'chzn-select'
        self.fields['action'].choices = self.ACTIONS.items()

        action_sent = data.get('action', None) if data else None
예제 #26
0
    def handle(self, *args, **kwargs):
        self.stdout.write('Creating permissions....')
        content_type = ContentType.objects.get_for_model(User)
        Permission.objects.get_or_create(codename='can_enter_data', name='Can enter data', content_type=content_type)
        Permission.objects.get_or_create(codename='can_view_batches', name='Can view Batches', content_type=content_type)
        Permission.objects.get_or_create(codename='can_view_interviewers', name='Can view Interviewers', content_type=content_type)
        Permission.objects.get_or_create(codename='can_view_aggregates', name='Can view Aggregates', content_type=content_type)
        Permission.objects.get_or_create(codename='view_completed_survey', name='Can view Completed Surveys', content_type=content_type)
        Permission.objects.get_or_create(codename='can_view_households', name='Can view Households', content_type=content_type)
        Permission.objects.get_or_create(codename='can_view_locations', name='Can view Locations', content_type=content_type)
        Permission.objects.get_or_create(codename='can_view_users', name='Can view Users', content_type=content_type)
        Permission.objects.get_or_create(codename='can_view_household_groups', name='Can view Household Groups', content_type=content_type)

        self.stdout.write('Permissions.')
        self.stdout.write('Creating answer definition... ')
        #ussd definition
        AnswerAccessDefinition.objects.get_or_create(channel=USSDAccess.choice_name(),
                                                     answer_type=NumericalAnswer.choice_name())
        AnswerAccessDefinition.objects.get_or_create(channel=USSDAccess.choice_name(),
                                                     answer_type=TextAnswer.choice_name())
        AnswerAccessDefinition.objects.get_or_create(channel=USSDAccess.choice_name(),
                                                     answer_type=MultiChoiceAnswer.choice_name())

        #ODK definition
        AnswerAccessDefinition.objects.get_or_create(channel=ODKAccess.choice_name(),
                                                     answer_type=NumericalAnswer.choice_name())
        AnswerAccessDefinition.objects.get_or_create(channel=ODKAccess.choice_name(),
                                                     answer_type=TextAnswer.choice_name())
        AnswerAccessDefinition.objects.get_or_create(channel=ODKAccess.choice_name(),
                                                     answer_type=MultiChoiceAnswer.choice_name())
        AnswerAccessDefinition.objects.get_or_create(channel=ODKAccess.choice_name(),
                                                     answer_type=MultiSelectAnswer.choice_name())
        AnswerAccessDefinition.objects.get_or_create(channel=ODKAccess.choice_name(),
                                                     answer_type=ImageAnswer.choice_name())
        AnswerAccessDefinition.objects.get_or_create(channel=ODKAccess.choice_name(),
                                                     answer_type=GeopointAnswer.choice_name())
        AnswerAccessDefinition.objects.get_or_create(channel=ODKAccess.choice_name(),
                                                     answer_type=DateAnswer.choice_name())
        AnswerAccessDefinition.objects.get_or_create(channel=ODKAccess.choice_name(),
                                                     answer_type=AudioAnswer.choice_name())
        AnswerAccessDefinition.objects.get_or_create(channel=ODKAccess.choice_name(),
                                                     answer_type=VideoAnswer.choice_name())

        #web form definition
        AnswerAccessDefinition.objects.get_or_create(channel=WebAccess.choice_name(),
                                                     answer_type=NumericalAnswer.choice_name())
        AnswerAccessDefinition.objects.get_or_create(channel=WebAccess.choice_name(),
                                                     answer_type=TextAnswer.choice_name())
        AnswerAccessDefinition.objects.get_or_create(channel=WebAccess.choice_name(),
                                                     answer_type=MultiChoiceAnswer.choice_name())
        AnswerAccessDefinition.objects.get_or_create(channel=WebAccess.choice_name(),
                                                     answer_type=MultiSelectAnswer.choice_name())
        AnswerAccessDefinition.objects.get_or_create(channel=WebAccess.choice_name(),
                                                     answer_type=ImageAnswer.choice_name())
        AnswerAccessDefinition.objects.get_or_create(channel=WebAccess.choice_name(),
                                                     answer_type=GeopointAnswer.choice_name())
        AnswerAccessDefinition.objects.get_or_create(channel=WebAccess.choice_name(),
                                                     answer_type=DateAnswer.choice_name())
        AnswerAccessDefinition.objects.get_or_create(channel=WebAccess.choice_name(),
                                                     answer_type=AudioAnswer.choice_name())
        AnswerAccessDefinition.objects.get_or_create(channel=WebAccess.choice_name(),
                                                     answer_type=VideoAnswer.choice_name())
        self.stdout.write('Successfully imported!')
 def test_logic_form_has_options_for_multi_type_questions(self):
     for answer_type in [MultiSelectAnswer.choice_name(), MultiChoiceAnswer.choice_name()]:            
         q = Question.objects.create(identifier=answer_type, text="text", answer_type=answer_type,
                                             qset_id=self.qset.id, response_validation_id=1)
         l = LogicForm(q)
         self.assertTrue(l.fields.get('option'))
 def get_summarised_answers(self):
     data = []
     q_opts = {}
     if self.specific_households is None:
         all_households = Household.objects.filter(listing__survey_houselistings__survey=self.survey)
     else:
         all_households = Household.objects.filter(pk__in=self.specific_households,
                                                   listing__survey_houselistings__survey=self.survey)
     locations = list(set(all_households.values_list('listing__ea__locations', flat=True)))
     for location_id in locations:
         households_in_location = all_households.filter(listing__ea__locations=location_id)
         household_location = Location.objects.get(id=location_id)
         location_ancestors = household_location.get_ancestors(include_self=True).\
             exclude(parent__isnull='country').values_list('name', flat=True)
         answers = []
         for household in households_in_location:
             for member in household.members.all():
                 try:
                     answers = list(location_ancestors)
                     member_gender = 'Male' if member.gender == HouseholdMember.MALE else 'Female'
                     answers.extend([household.listing.ea.name, household.house_number, '%s-%s' % (member.surname, member.first_name), str(member.age),
                                          member.date_of_birth.strftime(settings.DATE_FORMAT),
                                          member_gender])
                     for question in self.questions:
                         reply = member.reply(question)
                         if question.answer_type in [MultiChoiceAnswer.choice_name(), MultiSelectAnswer.choice_name()]\
                                 and self.multi_display == self.AS_LABEL:
                             label = q_opts.get((question.pk, reply), None)
                             if label is None:
                                 try:
                                     label = question.options.get(text__iexact=reply).order
                                 except QuestionOption.DoesNotExist:
                                     label = reply
                                 q_opts[(question.pk, reply)] = label
                             reply = str(label)
                         answers.append(reply.encode('utf8'))
                     data.append(answers)
                 except Exception, ex:
                     print 'Error ', str(ex)