Example #1
0
def _view_qset_data(request,
                    model_class,
                    interviews,
                    title,
                    disabled_fields=[]):
    params = request.GET if request.method == 'GET' else request.POST
    survey_filter = SurveyResultsFilterForm(model_class,
                                            disabled_fields=disabled_fields,
                                            data=params)
    locations_filter = LocationsFilterForm(data=request.GET, include_ea=True)
    selected_qset = None
    survey = None
    items_per_page = int(params.get('max_display_per_page', 50))
    try:
        page_index = int(params.get('page', 1)) - 1
    except BaseException:
        page_index = 0
    if survey_filter.is_valid():
        interviews = survey_filter.get_interviews(interviews=interviews)
        selected_qset = survey_filter.cleaned_data['question_set']
        survey = survey_filter.cleaned_data['survey']
    if locations_filter.is_valid():
        interviews = interviews.filter(
            ea__in=locations_filter.get_enumerations())
    search_fields = [
        'ea__name',
        'survey__name',
        'question_set__name',
        'answer__as_text',
    ]
    if 'q' in request.GET:
        interviews = get_filterset(interviews, request.GET['q'], search_fields)
    context = {
        'survey_filter': survey_filter,
        'interviews': interviews,
        'locations_filter': locations_filter,
        'location_filter_types': LocationType.in_between(),
        'placeholder': 'Response, EA, Survey, %s' % model_class.verbose_name(),
        'selected_qset': selected_qset,
        'model_class': model_class,
        'items_per_page': items_per_page,
        'max_display_per_page': items_per_page,
        'title': title
    }
    if selected_qset and survey:
        # page_start = page_index * items_per_page
        # interviews = interviews[page_start: page_start + items_per_page]()
        download_service = ResultsDownloadService(
            selected_qset,
            survey=survey,
            interviews=interviews,
            page_index=page_index,
            items_per_page=items_per_page)
        df = download_service.get_interview_answers()
        context['report'] = mark_safe(
            df.to_html(classes='table table-striped\
                    dataTable table-bordered table-hover table-sort',
                       max_rows=items_per_page))
    return render(request, 'question_set/view_all_data.html', context)
Example #2
0
def _create_or_edit(request, action_text, interviewer=None):
    request.breadcrumbs([
        ('Interviewers', reverse('interviewers_page')),
    ])
    title = 'New Interviewer'
    odk_instance = None
    data = request.GET
    if request.POST and request.POST.get('ea'):
        ea = get_object_or_404(EnumerationArea, pk=request.POST['ea'])
        data = dict([(loc.type.name, loc.pk) for loc in ea.parent_locations()])
    if interviewer:
        extra = 0
        title = 'Edit Interviewer'
        odk_accesses = interviewer.odk_access
        if odk_accesses.exists():
            odk_instance = odk_accesses[0]
        data = data or dict([(loc.type.name, loc.pk) for loc in interviewer.ea.parent_locations()])
    else:
        extra = 1
    locations_filter = LocationsFilterForm(data=data)
    if data:
        eas = locations_filter.get_enumerations()
    else:
        eas = EnumerationArea.objects.none()
    USSDAccessFormSet = inlineformset_factory(Interviewer, USSDAccess, form=USSDAccessForm, extra=extra)
    ussd_access_form = USSDAccessFormSet(prefix='ussd_access', instance=interviewer)
    response = None
    redirect_url = reverse('interviewers_page')
    odk_access_form = ODKAccessForm(instance=odk_instance)
    if request.method == 'POST':
        interviewer_form = InterviewerForm(eas, data=request.POST, instance=interviewer)
        ussd_access_form = USSDAccessFormSet(request.POST, prefix='ussd_access', instance=interviewer)
#         odk_access_form = ODKAccessFormSet(request.POST, prefix='odk_access', instance=interviewer)
        odk_access_form = ODKAccessForm(request.POST, instance=odk_instance)
        if interviewer_form.is_valid() and ussd_access_form.is_valid() and odk_access_form.is_valid():
            interviewer = interviewer_form.save()
            ussd_access_form.instance = interviewer
            ussd_access_form.save()
            odk_access = odk_access_form.save(commit=False) 
            odk_access.interviewer = interviewer
            odk_access.save()
            messages.success(request, "Interviewer successfully %sed." % action_text )
            return HttpResponseRedirect(redirect_url)
    else:
        interviewer_form = InterviewerForm(eas, instance=interviewer)
    loc_types = LocationType.in_between()
    return response or render(request, 'interviewers/interviewer_form.html', {'country_phone_code': COUNTRY_PHONE_CODE,
                                                                  'form': interviewer_form,
                                                                  'ussd_access_form' : ussd_access_form,
                                                                  'odk_access_form' : odk_access_form, 
                                                                  'title': title,
                                                                  'id': "create-interviewer-form",
                                                                  'class': 'interviewer-form',
                                                                  'button_label': "Save",
                                                                  'cancel_url': redirect_url,
                                                                  'locations_filter': locations_filter,
                                                                  'location_filter_types' : loc_types,
                                                                  'loading_text': "Creating..."})
def show_interviewer_completion_summary(request):
    params = request.GET
    selected_location = None
    selected_ea = None
    interviewers = Interviewer.objects.order_by('id')
    search_fields = ['name', 'ea__name']
    if request.GET.has_key('q'):
        interviewers = get_filterset(interviewers, request.GET['q'], search_fields)
    if params.has_key('status'):
        interviewers = interviewers.intervieweraccess.filter(is_active=ast.literal_eval(params['status']))
    locations_filter = LocFilterForm(data=request.GET, include_ea=True)
    if locations_filter.is_valid():
        print 'locations count: ', locations_filter.get_enumerations().count()
        interviewers = interviewers.filter(ea__in=locations_filter.get_enumerations()).order_by('name')
    return render(request, 'aggregates/interviewers_summary.html',
                  {'interviewers': interviewers,
                    'locations_filter' : locations_filter,
                   'request': request})
def enumeration_area_filter(request):
    locations_filter = LocationsFilterForm(data=request.GET)
    enumeration_areas = locations_filter.get_enumerations()
    eas = enumeration_areas.values(
        'id',
        'name',
    ).order_by('name')
    json_dump = json.dumps(list(eas), cls=DjangoJSONEncoder)
    return HttpResponse(json_dump, content_type='application/json')
def show_interviewer_completion_summary(request):
    params = request.GET
    selected_location = None
    selected_ea = None
    interviewers = Interviewer.objects.order_by('id')
    search_fields = ['name', 'ea__name']
    if request.GET.has_key('q'):
        interviewers = get_filterset(interviewers, request.GET['q'], search_fields)
    if params.has_key('status'):
        interviewers = interviewers.intervieweraccess.filter(is_active=ast.literal_eval(params['status']))
    locations_filter = LocFilterForm(data=request.GET, include_ea=True)
    if locations_filter.is_valid():
        print 'locations count: ', locations_filter.get_enumerations().count()
        interviewers = interviewers.filter(ea__in=locations_filter.get_enumerations()).order_by('name')
    return render(request, 'aggregates/interviewers_summary.html',
                  {'interviewers': interviewers,
                    'locations_filter' : locations_filter,
                   'request': request})
Example #6
0
def save(request, instance=None):
    head = None
    if instance:
        handler = reverse('edit_household_page', args=(instance.pk, ))
        head = instance.get_head()
        heading = 'Edit Household'
        cancel_url = reverse('view_household_page', args=(instance.pk, ))
    else:
        handler = reverse('new_household_page')
        heading = 'New Household'
        cancel_url = reverse('list_household_page')
    locations_filter = LocationsFilterForm(data=request.GET, include_ea=True)
    householdform = HouseholdForm(instance=instance, eas=locations_filter.get_enumerations())
    headform = HouseholdHeadForm(instance=head)
    if request.method == 'POST':
        householdform = HouseholdForm(data=request.POST, instance=instance)
        headform = HouseholdHeadForm(data=request.POST, instance=head)
        if householdform.is_valid():
            household = householdform.save(commit=False)
            interviewer = household.last_registrar
            survey = SurveyAllocation.get_allocation(interviewer)
            if survey:
                survey_listing = SurveyHouseholdListing.get_or_create_survey_listing(interviewer, survey)
                household.listing = survey_listing.listing
                household.save()
                householdform = HouseholdForm()
                # import pdb; pdb.set_trace()
                if headform.is_valid():
                    head = headform.save(commit=False)
                    head.household = household
                    head.registrar = interviewer
                    head.survey_listing = survey_listing
                    head.registration_channel = WebAccess.choice_name()
                    head.save()
                    if household.head_desc is not head.surname:
                        household.head_desc = head.surname
                        household.save()
                    messages.info(request, 'Household %s saved successfully' % household.house_number)
                    return HttpResponseRedirect(reverse('view_household_page', args=(household.pk, )))
                handler = reverse('new_household_page')
            else:
                messages.error(request, 'No open survey for %s' % interviewer.name)
    context = {
               'headform': headform,
               'householdform': householdform,
               'action': handler,
                'cancel_url' : cancel_url,
               'heading':heading,
               'id': "create-household-form",
               'button_label': "Save",
               'loading_text': "Creating...",
               'locations_filter' : locations_filter}
    request.breadcrumbs([
        ('Households', reverse('list_household_page')),
    ])
    return render(request, 'households/new.html', context)
Example #7
0
def household_filter(request):
    locations_filter = LocationsFilterForm(request.GET, include_ea=True)
    enumeration_areas = locations_filter.get_enumerations()
    all_households = Household.objects.filter(ea__in=enumeration_areas).order_by('household_member__householdhead__surname')
    search_fields = ['house_number', 'listing__ea__name', 'last_registrar__name', 'listing__initial_survey__name', ]
    if request.GET.has_key('q'):
        all_households = get_filterset(all_households, request.GET['q'], search_fields)
    all_households =  all_households.values('id', 'house_number', ).order_by('name')
    json_dump = json.dumps(list(all_households), cls=DjangoJSONEncoder)
    return HttpResponse(json_dump, mimetype='application/json')
Example #8
0
def _view_qset_data(request, model_class, interviews,title, disabled_fields=[]):
    params = request.GET if request.method == 'GET' else request.POST
    survey_filter = SurveyResultsFilterForm(
        model_class, disabled_fields=disabled_fields, data=params)
    locations_filter = LocationsFilterForm(data=request.GET, include_ea=True)
    selected_qset = None
    survey = None
    items_per_page = int(params.get('max_display_per_page', 50))
    try:
        page_index = int(params.get('page', 1)) - 1
    except BaseException:
        page_index = 0
    if survey_filter.is_valid():
        interviews = survey_filter.get_interviews(interviews=interviews)
        selected_qset = survey_filter.cleaned_data['question_set']
        survey = survey_filter.cleaned_data['survey']
    if locations_filter.is_valid():
        interviews = interviews.filter(ea__in=locations_filter.get_enumerations())
    search_fields = [
        'ea__name',
        'survey__name',
        'question_set__name',
        'answer__as_text',
    ]
    if 'q' in request.GET:
        interviews = get_filterset(interviews, request.GET['q'], search_fields)
    context = {
        'survey_filter': survey_filter,
        'interviews': interviews,
        'locations_filter': locations_filter,
        'location_filter_types': LocationType.in_between(),
        'placeholder': 'Response, EA, Survey, %s' % model_class.verbose_name(),
        'selected_qset': selected_qset,
        'model_class': model_class,
        'items_per_page': items_per_page,
        'max_display_per_page': items_per_page,
        'title':title}
    if selected_qset and survey:
        # page_start = page_index * items_per_page
        # interviews = interviews[page_start: page_start + items_per_page]()
        download_service = ResultsDownloadService(
            selected_qset,
            survey=survey,
            interviews=interviews,
            page_index=page_index,
            items_per_page=items_per_page)
        df = download_service.get_interview_answers()
        context['report'] = mark_safe(
            df.to_html(
                classes='table table-striped\
                    dataTable table-bordered table-hover table-sort',
                max_rows=items_per_page))
    return render(request, 'question_set/view_all_data.html', context)
Example #9
0
def index(request):
    locations_filter = LocationsFilterForm(data=request.GET)
    enumeration_areas = locations_filter.get_enumerations()
    search_fields = ['name', 'locations__name', ]
    if 'q' in request.GET:
        enumeration_areas = get_filterset(
            enumeration_areas, request.GET['q'], search_fields)
    loc_types = LocationType.in_between()
    context = {'enumeration_areas': enumeration_areas,
               'locations_filter': locations_filter,
               'location_filter_types': loc_types,
               'placeholder': 'name, location name'}
    return render(request, "enumeration_area/index.html", context)
Example #10
0
def index(request):
    locations_filter = LocationsFilterForm(data=request.GET)
    enumeration_areas = locations_filter.get_enumerations()
    search_fields = ['name', 'locations__name', ]
    if request.GET.has_key('q'):
        enumeration_areas = get_filterset(enumeration_areas, request.GET['q'], search_fields)
    loc_types = LocationType.in_between()
    context = {'enumeration_areas': enumeration_areas,
               'locations_filter' : locations_filter,
               'location_filter_types' : loc_types,
               'placeholder': 'name, location name',
               'max_display_per_page': settings.MAX_DISPLAY_PER_PAGE}
    return render(request, "enumeration_area/index.html", context)
Example #11
0
 def test_locations_filter_form(self):
     ea = EnumerationArea.objects.last()
     location = ea.locations.first()
     ea_locations = location.get_ancestors(include_self=True)
     data = {location.type.name: location.id for location in ea_locations}
     location_filter = LocationsFilterForm(data=data)
     self.assertNotIn('enumeration_area', location_filter.fields)
     eas = location_filter.get_enumerations()
     # eas basically returns all EAs as per the immediate parent to the smallest unit
     self.assertEquals(
         eas.count(),
         EnumerationArea.objects.filter(
             locations__parent__in=ea_locations).distinct().count())
     self.assertEquals(eas.filter(id=ea.id).count(), 1)
     location_filter = LocationsFilterForm(data=data, include_ea=True)
     self.assertEquals(eas.filter(id=ea.id).count(), 1)
     self.assertIn('enumeration_area', location_filter.fields)
     data['enumeration_area'] = ea.id
     location_filter = LocationsFilterForm(data=data, include_ea=True)
     self.assertTrue(location_filter.is_valid())
     eas = location_filter.get_enumerations()
     self.assertEquals(eas.count(), 1)
Example #12
0
def index(request):
    locations_filter = LocationsFilterForm(data=request.GET)
    enumeration_areas = locations_filter.get_enumerations()
    search_fields = ['name', 'locations__name', ]
    if request.GET.has_key('q'):
        enumeration_areas = get_filterset(enumeration_areas, request.GET['q'], search_fields)
    loc_types = LocationType.in_between()
    context = {'enumeration_areas': enumeration_areas,
               'locations_filter' : locations_filter,
               'location_filter_types' : loc_types,
               'placeholder': 'name, location name',
               'max_display_per_page': settings.MAX_DISPLAY_PER_PAGE}
    return render(request, "enumeration_area/index.html", context)
Example #13
0
def list_households(request):
    locations_filter = LocationsFilterForm(data=request.GET, include_ea=True)
    enumeration_areas = locations_filter.get_enumerations()
    households = Household.objects.filter(listing__ea__in=enumeration_areas).order_by('house_number')
    search_fields = ['house_number', 'listing__ea__name', 'last_registrar__name', 'listing__initial_survey__name', ]
    if request.GET.has_key('q'):
        households = get_filterset(households, request.GET['q'], search_fields)
    return render(request, 'households/index.html',
                  {'households': households, 
                   'locations_filter' : locations_filter, 
                   'location_filter_types' : LocationType.in_between(),
                   'Largest Unit' : LocationType.largest_unit(),
                   'placeholder': 'house no, ea, survey, interviewer',
                   'request': request})
def index(request):
    locations_filter = LocationsFilterForm(data=request.GET)
    enumeration_areas = locations_filter.get_enumerations()
    search_fields = [
        'name',
        'locations__name',
    ]
    if 'q' in request.GET:
        enumeration_areas = get_filterset(enumeration_areas, request.GET['q'],
                                          search_fields)
    loc_types = LocationType.in_between()
    context = {
        'enumeration_areas': enumeration_areas,
        'locations_filter': locations_filter,
        'location_filter_types': loc_types,
        'placeholder': 'name, location name'
    }
    return render(request, "enumeration_area/index.html", context)
Example #15
0
def list_interviewers(request):
    params = request.GET
    locations_filter = LocationsFilterForm(data=request.GET, include_ea=True)
    if locations_filter.is_valid():
        interviewers = Interviewer.objects.filter(ea__in=locations_filter.get_enumerations()).order_by('name')
    else:
        interviewers = Interviewer.objects.all()
    search_fields = ['name', 'intervieweraccess__user_identifier']
    if request.GET.has_key('q'):
        interviewers = get_filterset(interviewers, request.GET['q'], search_fields)
    if params.has_key('status'):
        interviewers = interviewers.filter(is_blocked=ast.literal_eval(params['status']))
    loc_types = LocationType.in_between()
    return render(request, 'interviewers/index.html',
                  {'interviewers': interviewers,
                   'locations_filter' : locations_filter,
                   'location_filter_types' : loc_types,
                   'placeholder': 'name, mobile numbers, odk id',
                   'request': request})
Example #16
0
def household_filter(request):
    locations_filter = LocationsFilterForm(request.GET, include_ea=True)
    enumeration_areas = locations_filter.get_enumerations()
    all_households = Household.objects.filter(
        ea__in=enumeration_areas).order_by(
            'household_member__householdhead__surname')
    search_fields = [
        'house_number',
        'listing__ea__name',
        'last_registrar__name',
        'listing__initial_survey__name',
    ]
    if request.GET.has_key('q'):
        all_households = get_filterset(all_households, request.GET['q'],
                                       search_fields)
    all_households = all_households.values(
        'id',
        'house_number',
    ).order_by('name')
    json_dump = json.dumps(list(all_households), cls=DjangoJSONEncoder)
    return HttpResponse(json_dump, content_type='application/json')
Example #17
0
def list_households(request):
    locations_filter = LocationsFilterForm(data=request.GET, include_ea=True)
    enumeration_areas = locations_filter.get_enumerations()
    households = Household.objects.filter(
        listing__ea__in=enumeration_areas).order_by('house_number')
    search_fields = [
        'house_number',
        'listing__ea__name',
        'last_registrar__name',
        'listing__initial_survey__name',
    ]
    if request.GET.has_key('q'):
        households = get_filterset(households, request.GET['q'], search_fields)
    return render(
        request, 'households/index.html', {
            'households': households,
            'locations_filter': locations_filter,
            'location_filter_types': LocationType.in_between(),
            'Largest Unit': LocationType.largest_unit(),
            'placeholder': 'house no, ea, survey, interviewer',
            'request': request
        })
Example #18
0
def download_data(request, qset_id):
    qset = QuestionSet.get(pk=qset_id)
    params = request.GET if request.method == 'GET' else request.POST
    survey_filter = QuestionSetResultsFilterForm(qset, data=params)
    locations_filter = LocationsFilterForm(data=request.GET, include_ea=True)
    interviews = survey_filter.get_interviews()
    if locations_filter.is_valid():
        interviews = interviews.filter(
            ea__in=locations_filter.get_enumerations()).order_by('created')
    last_selected_loc = locations_filter.last_location_selected
    download_service = ResultsDownloadService(qset, interviews=interviews)
    file_name = '%s%s' % ('%s-%s-' %
                          (last_selected_loc.type.name, last_selected_loc.name)
                          if last_selected_loc else '', qset.name)
    reports_df = download_service.generate_interview_reports()
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment;\
        filename="%s.csv"' % file_name
    reports_df.to_csv(response,
                      date_format='%Y-%m-%d %H:%M:%S',
                      encoding='utf-8')  # exclude interview id
    return response
Example #19
0
def list_interviewers(request):
    params = request.GET
    locations_filter = LocationsFilterForm(data=request.GET, include_ea=True)
    if locations_filter.is_valid():
        interviewers = Interviewer.objects.filter(
            ea__in=locations_filter.get_enumerations())
    else:
        interviewers = Interviewer.objects.all()
    search_fields = ['name', 'intervieweraccess__user_identifier']
    if 'q' in request.GET:
        interviewers = get_filterset(
            interviewers, request.GET['q'], search_fields)
    if 'status' in params:
        interviewers = interviewers.filter(
            is_blocked=ast.literal_eval(params['status']))
    loc_types = LocationType.in_between()
    return render(request, 'interviewers/index.html',
                  {'interviewers': interviewers.order_by('name'),
                   'locations_filter': locations_filter,
                   'location_filter_types': loc_types,
                   'placeholder': 'name, mobile numbers, odk id',
                   'request': request})
Example #20
0
def download_data(request, qset_id):
    qset = QuestionSet.get(pk=qset_id)
    params = request.GET if request.method == 'GET' else request.POST
    survey_filter = QuestionSetResultsFilterForm(qset, data=params)
    locations_filter = LocationsFilterForm(data=request.GET, include_ea=True)
    interviews = survey_filter.get_interviews()
    if locations_filter.is_valid():
        interviews = interviews.filter(
            ea__in=locations_filter.get_enumerations()).order_by('created')
    last_selected_loc = locations_filter.last_location_selected
    download_service = ResultsDownloadService(qset, interviews=interviews)
    file_name = '%s%s' % ('%s-%s-' % (
        last_selected_loc.type.name,
        last_selected_loc.name) if last_selected_loc else '',
        qset.name)
    reports_df = download_service.generate_interview_reports()
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment;\
        filename="%s.csv"' % file_name
    reports_df.to_csv(
        response,
        date_format='%Y-%m-%d %H:%M:%S',
        encoding='utf-8')  # exclude interview id
    return response
Example #21
0
def save(request, instance=None):
    head = None
    if instance:
        handler = reverse('edit_household_page', args=(instance.pk, ))
        head = instance.get_head()
        heading = 'Edit Household'
        cancel_url = reverse('view_household_page', args=(instance.pk, ))
    else:
        handler = reverse('new_household_page')
        heading = 'New Household'
        cancel_url = reverse('list_household_page')
    locations_filter = LocationsFilterForm(data=request.GET, include_ea=True)
    householdform = HouseholdForm(instance=instance,
                                  eas=locations_filter.get_enumerations())
    headform = HouseholdHeadForm(instance=head)
    if request.method == 'POST':
        householdform = HouseholdForm(data=request.POST, instance=instance)
        headform = HouseholdHeadForm(data=request.POST, instance=head)
        if householdform.is_valid():
            household = householdform.save(commit=False)
            interviewer = household.last_registrar
            survey = SurveyAllocation.get_allocation(interviewer)
            if survey:
                survey_listing = SurveyHouseholdListing.get_or_create_survey_listing(
                    interviewer, survey)
                household.listing = survey_listing.listing
                household.save()
                householdform = HouseholdForm()
                # import pdb; pdb.set_trace()
                if headform.is_valid():
                    head = headform.save(commit=False)
                    head.household = household
                    head.registrar = interviewer
                    head.survey_listing = survey_listing
                    head.registration_channel = WebAccess.choice_name()
                    head.save()
                    if household.head_desc is not head.surname:
                        household.head_desc = head.surname
                        household.save()
                    messages.info(
                        request, 'Household %s saved successfully' %
                        household.house_number)
                    return HttpResponseRedirect(
                        reverse('view_household_page', args=(household.pk, )))
                handler = reverse('new_household_page')
            else:
                messages.error(request,
                               'No open survey for %s' % interviewer.name)
    context = {
        'headform': headform,
        'householdform': householdform,
        'action': handler,
        'cancel_url': cancel_url,
        'heading': heading,
        'id': "create-household-form",
        'button_label': "Save",
        'loading_text': "Creating...",
        'locations_filter': locations_filter
    }
    request.breadcrumbs([
        ('Households', reverse('list_household_page')),
    ])
    return render(request, 'households/new.html', context)
Example #22
0
def enumeration_area_filter(request):
    locations_filter = LocationsFilterForm(data=request.GET)
    enumeration_areas = locations_filter.get_enumerations()
    eas =  enumeration_areas.values('id', 'name', ).order_by('name')
    json_dump = json.dumps(list(eas), cls=DjangoJSONEncoder)
    return HttpResponse(json_dump, mimetype='application/json')
Example #23
0
def _create_or_edit(request, action_text, interviewer=None):
    extra = 1
    request.breadcrumbs([
        ('Interviewers', reverse('interviewers_page')),
    ])
    extra = 1
    title = 'New Interviewer'
    odk_instance = None
    data = request.GET
    if request.POST and request.POST.get('ea'):
        ea = get_object_or_404(EnumerationArea, pk=request.POST['ea'])
        data = dict([(loc.type.name, loc.pk) for loc in ea.parent_locations()])
    if interviewer:
        title = 'Edit Interviewer'
        odk_accesses = interviewer.odk_access
        if odk_accesses.exists():
            odk_instance = odk_accesses[0]
        data = data or dict([(loc.type.name, loc.pk)
                             for loc in interviewer.ea.parent_locations()])
        if interviewer.ussd_access.exists():
            extra = 0
    locations_filter = LocationsFilterForm(data=data)
    if data:
        eas = locations_filter.get_enumerations()
    else:
        eas = EnumerationArea.objects.none()
    USSDAccessFormSet = inlineformset_factory(Interviewer,
                                              USSDAccess,
                                              form=USSDAccessForm,
                                              extra=extra)
    ussd_access_form = USSDAccessFormSet(prefix='ussd_access',
                                         instance=interviewer)
    response = None
    redirect_url = reverse('interviewers_page')
    odk_access_form = ODKAccessForm(instance=odk_instance)
    if request.method == 'POST':
        interviewer_form = InterviewerForm(eas,
                                           data=request.POST,
                                           instance=interviewer)
        ussd_access_form = USSDAccessFormSet(request.POST,
                                             prefix='ussd_access',
                                             instance=interviewer)
        #         odk_access_form = ODKAccessFormSet(request.POST, prefix='odk_access', instance=interviewer)
        odk_access_form = ODKAccessForm(request.POST, instance=odk_instance)
        if interviewer_form.is_valid() and odk_access_form.is_valid():
            interviewer = interviewer_form.save()
            ussd_access_form.instance = interviewer
            if ussd_access_form.is_valid():
                ussd_access_form.save()
                odk_access = odk_access_form.save(commit=False)
                odk_access.interviewer = interviewer
                odk_access.save()
                messages.success(
                    request, "Interviewer successfully %sed." % action_text)
            return HttpResponseRedirect(redirect_url)
    else:
        interviewer_form = InterviewerForm(eas, instance=interviewer)
    loc_types = LocationType.in_between()
    return response or render(
        request, 'interviewers/interviewer_form.html', {
            'form': interviewer_form,
            'ussd_access_form': ussd_access_form,
            'odk_access_form': odk_access_form,
            'title': title,
            'id': "create-interviewer-form",
            'class': 'interviewer-form',
            'button_label': "Save",
            'cancel_url': redirect_url,
            'locations_filter': locations_filter,
            'location_filter_types': loc_types,
            'loading_text': "Creating..."
        })