Exemple #1
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'
Exemple #2
0
 def setUp(self):
     self.client = Client()
     user_without_permission = User.objects.create_user(
         username='******', email='*****@*****.**', password='******')
     raj = self.assign_permission_to(
         User.objects.create_user('demo12', '*****@*****.**', 'demo12'),
         'can_view_batches')
     self.listing_form = mommy.make(ListingTemplate)
     question1 = mommy.make(Question,
                            qset=self.listing_form,
                            answer_type=NumericalAnswer.choice_name())
     question2 = mommy.make(Question,
                            qset=self.listing_form,
                            answer_type=TextAnswer.choice_name())
     question3 = mommy.make(Question,
                            qset=self.listing_form,
                            answer_type=VideoAnswer.choice_name())
     self.client.login(username='******', password='******')
     self.form_data = {
         'name':
         'survey demo12',
         'description':
         'survey description demo12',
         'has_sampling':
         True,
         'sample_size':
         10,
         'random_sample_label':
         'q1 {{%s}} q2: {{%s}}' %
         (question1.identifier, question2.identifier)
     }
Exemple #3
0
def save_survey_questions(survey_allocation, xml_blob, media_files):
    survey_tree = _get_tree_from_blob(xml_blob)
    interviewer = survey_allocation.interviewer
    survey = survey_allocation.survey
    form_id = _get_form_id(survey_tree)
    member = _get_or_create_household_member(survey_allocation, survey_tree)
    response_dict = _get_responses(interviewer, survey_tree, survey)
    treated_batches = {}
    interviews = {}
    if response_dict:
        for (b_id, q_id), answers in response_dict.items():
            question = Question.objects.get(pk=q_id)
            batch = treated_batches.get(b_id, Batch.objects.get(pk=b_id))
            loop_id = Answer.NO_LOOP
            for idx, answer in enumerate(answers):
                if len(answers) > 0:
                    loop_id = idx
                if answer is not None:
                    if question.answer_type in [
                            AudioAnswer.choice_name(),
                            ImageAnswer.choice_name(),
                            VideoAnswer.choice_name()
                    ]:
                        answer = media_files.get(answer, None)
                    interview = interviews.get(b_id, None)
                    if interview is None:
                        interview, _ = Interview.objects.get_or_create(
                            interviewer=interviewer,
                            householdmember=member,
                            batch=batch,
                            interview_channel=interviewer.odk_access[0],
                            ea=survey_allocation.allocation_ea)
                        interviews[b_id] = interview
                    created = record_interview_answer(interview, question,
                                                      answer, loop_id)
            if b_id not in treated_batches.keys():
                treated_batches[b_id] = batch
        map(lambda batch: member.batch_completed(batch),
            treated_batches.values()
            )  #create batch completion for question batches
        member.survey_completed()
        if member.household.has_completed(survey):
            map(
                lambda batch: member.household.batch_completed(
                    batch, interviewer), treated_batches.values())
            member.household.survey_completed(survey, interviewer)
    household = member.household
    submission = ODKSubmission.objects.create(
        interviewer=interviewer,
        survey=survey,
        form_id=form_id,
        description=SURVEY_DESC,
        instance_id=_get_instance_id(survey_tree),
        household_member=member,
        household=household,
        xml=etree.tostring(survey_tree, pretty_print=True))
    #    execute.delay(submission.save_attachments, media_files)
    submission.save_attachments(media_files.values())
    return submission
Exemple #4
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'
 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 _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_only_ussd_question_types_are_used_form_randomization(self):
     self.assertEquals(Survey.objects.count(), 0)
     self.test_new_should_create_survey_on_post()
     survey = Survey.objects.first()
     self.failUnless(survey)
     sampling_criteria_url = reverse('listing_criteria_page', args=(survey.id,))
     form_data = {'survey': survey.id, 'validation_test': 'equals',
                  'value': 1,
                  'listing_question': self.listing_form.questions.get(answer_type=VideoAnswer.choice_name()).id,}
     self.assertEquals(survey.randomization_criteria.count(), 0)     # confirm nothin exists
     response = self.client.post(sampling_criteria_url, data=form_data)
     self.assertEquals(survey.randomization_criteria.count(), 0)     # confirm nothin exists
     self.assertEquals(response.context['sampling_form'].is_valid(), False)
 def setUp(self):
     self.client = Client()
     user_without_permission = User.objects.create_user(username='******', email='*****@*****.**',
                                                        password='******')
     raj = self.assign_permission_to(User.objects.create_user('demo12', '*****@*****.**', 'demo12'),
                                     'can_view_batches')
     self.listing_form = mommy.make(ListingTemplate)
     question1 = mommy.make(Question, qset=self.listing_form, answer_type=NumericalAnswer.choice_name())
     question2 = mommy.make(Question, qset=self.listing_form, answer_type=TextAnswer.choice_name())
     question3 = mommy.make(Question, qset=self.listing_form, answer_type=VideoAnswer.choice_name())
     self.client.login(username='******', password='******')
     self.form_data = {'name': 'survey demo12', 'description': 'survey description demo12',
                       'has_sampling': True, 'sample_size': 10,
                       'random_sample_label': 'q1 {{%s}} q2: {{%s}}' % (question1.identifier, question2.identifier)}
Exemple #9
0
 def test_only_ussd_question_types_are_used_form_randomization(self):
     self.assertEquals(Survey.objects.count(), 0)
     self.test_new_should_create_survey_on_post()
     survey = Survey.objects.first()
     self.failUnless(survey)
     sampling_criteria_url = reverse('listing_criteria_page',
                                     args=(survey.id, ))
     form_data = {
         'survey':
         survey.id,
         'validation_test':
         'equals',
         'value':
         1,
         'listing_question':
         self.listing_form.questions.get(
             answer_type=VideoAnswer.choice_name()).id,
     }
     self.assertEquals(survey.randomization_criteria.count(),
                       0)  # confirm nothin exists
     response = self.client.post(sampling_criteria_url, data=form_data)
     self.assertEquals(survey.randomization_criteria.count(),
                       0)  # confirm nothin exists
     self.assertEquals(response.context['sampling_form'].is_valid(), False)
Exemple #10
0
def process_submission(interviewer, xml_file, media_files=[], request=None):
    """
    extract surveys and for this xml file and for specified household member
    """
    media_files = dict([(os.path.basename(f.name), f) for f in media_files])
    reports = []
    survey_tree = _get_tree(xml_file)
    form_id = _get_form_id(survey_tree)
    survey = _get_survey(survey_tree)
    survey_allocation = get_survey_allocation(interviewer)
    household = None
    member = None
    survey_listing = SurveyHouseholdListing.get_or_create_survey_listing(interviewer, survey)
    if _get_form_type(survey_tree) == LISTING:
        households = save_household_list(interviewer, survey, survey_tree, survey_listing)
        survey_allocation.stage = SurveyAllocation.SURVEY
        survey_allocation.save()
        for household in households:
            submission = ODKSubmission.objects.create(
                interviewer=interviewer,
                survey=survey,
                form_id=form_id,
                description=LISTING_DESC,
                instance_id=_get_instance_id(survey_tree),
                household_member=member,
                household=household,
                xml=etree.tostring(survey_tree, pretty_print=True),
            )
    elif _get_form_type(survey_tree) == NON_RESPONSE:
        non_responses = save_nonresponse_answers(interviewer, survey, survey_tree, survey_listing)
        for non_response in non_responses:
            submission = ODKSubmission.objects.create(
                interviewer=interviewer,
                survey=survey,
                form_id=form_id,
                description=NON_RESPONSE_DESC,
                instance_id=_get_instance_id(survey_tree),
                household_member=member,
                household=non_response.household,
                xml=etree.tostring(survey_tree, pretty_print=True),
            )
    else:
        member = _get_or_create_household_member(interviewer, survey, survey_tree)
        response_dict = _get_responses(interviewer, survey_tree, survey)
        treated_batches = {}
        interviews = {}
        if response_dict:
            for (b_id, q_id), answer in response_dict.items():
                question = Question.objects.get(pk=q_id)
                batch = treated_batches.get(b_id, Batch.objects.get(pk=b_id))
                if answer is not None:
                    if question.answer_type in [
                        AudioAnswer.choice_name(),
                        ImageAnswer.choice_name(),
                        VideoAnswer.choice_name(),
                    ]:
                        answer = media_files.get(answer, None)
                    interview = interviews.get(b_id, None)
                    if interview is None:
                        interview, _ = Interview.objects.get_or_create(
                            interviewer=interviewer,
                            householdmember=member,
                            batch=batch,
                            interview_channel=interviewer.odk_access[0],
                            ea=interviewer.ea,
                        )

                        interviews[b_id] = interview
                    created = record_interview_answer(interview, question, answer)
                if b_id not in treated_batches.keys():
                    treated_batches[b_id] = batch
            map(
                lambda batch: member.batch_completed(batch), treated_batches.values()
            )  # create batch completion for question batches
            member.survey_completed()
            if member.household.has_completed(survey):
                map(lambda batch: member.household.batch_completed(batch, interviewer), treated_batches.values())
                member.household.survey_completed(survey, interviewer)
        household = member.household
        submission = ODKSubmission.objects.create(
            interviewer=interviewer,
            survey=survey,
            form_id=form_id,
            description=SURVEY_DESC,
            instance_id=_get_instance_id(survey_tree),
            household_member=member,
            household=household,
            xml=etree.tostring(survey_tree, pretty_print=True),
        )
        #    execute.delay(submission.save_attachments, media_files)
        submission.save_attachments(media_files.values())
    return submission
    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!')