def import_questions(request):
    """
    Imports an XLS or CSV file into the user's SurveyDraft list.
    Returns an error in JSON if the survey was not valid.
    """
    output = {}
    posted_file = request.FILES.get(u'files')
    response_code = 200
    if posted_file:
        posted_file.seek(0)

        if posted_file.content_type in XLS_CONTENT_TYPES:
            imported_sheets_as_csv = pyxform_utils.convert_xls_to_csv_string(posted_file)
        elif posted_file.content_type == "text/csv":
            imported_sheets_as_csv = posted_file.read()
        else:
            raise Exception("Content-type not recognized: '%s'" % posted_file.content_type)

        split_surveys = xlform.split_apart_survey(imported_sheets_as_csv)

        new_survey_drafts = []
        for _split_survey in split_surveys:
            sd = SurveyDraft(name='New Form',
                             body=_split_survey[0],
                             user=request.user,
                             asset_type='question')
            sd._summarize()
            new_survey_drafts.append(sd)
        SurveyDraft.objects.bulk_create(new_survey_drafts)

        output[u'survey_draft_id'] = -1
    else:
        response_code = 204  # Error 204: No input
        output[u'error'] = "No file posted"
    return HttpResponse(json.dumps(output), content_type="application/json", status=response_code)
def import_questions(request):
    """
    Imports an XLS or CSV file into the user's SurveyDraft list.
    Returns an error in JSON if the survey was not valid.
    """
    output = {}
    posted_file = request.FILES.get(u'files')
    response_code = 200
    if posted_file:
        posted_file.seek(0)

        if posted_file.content_type in XLS_CONTENT_TYPES:
            imported_sheets_as_csv = pyxform_utils.convert_xls_to_csv_string(posted_file)
        elif posted_file.content_type == "text/csv":
            imported_sheets_as_csv = posted_file.read()
        else:
            raise Exception("Content-type not recognized: '%s'" % posted_file.content_type)

        split_surveys = xlform.split_apart_survey(imported_sheets_as_csv)

        new_survey_drafts = []
        for _split_survey in split_surveys:
            sd = SurveyDraft(name='New Form',
                             body=_split_survey[0],
                             user=request.user,
                             asset_type='question')
            sd._summarize()
            new_survey_drafts.append(sd)
        SurveyDraft.objects.bulk_create(new_survey_drafts)

        output[u'survey_draft_id'] = -1
    else:
        response_code = 204  # Error 204: No input
        output[u'error'] = "No file posted"
    return HttpResponse(json.dumps(output), content_type="application/json", status=response_code)
Exemple #3
0
 def test_split_into_individual_surveys(self):
     split_surveys = xlform.split_apart_survey(_stripped(example_3q))
     self.assertEqual(len(split_surveys), 3)