class TestSurvey(TestCase): def setUp(self): self.Sv = Survey() self.Sv.name = "Plantas" self.Sv.description = "ya jale todo" self.Sv.save() self.Qs = Question() self.Qs.question_text = "¿es GG?" self.Qs.survey = self.Sv self.Rs = Response() self.name = "Carlos" self.survey = self.Sv self.BRs = BaseResponse() self.BRs.response = self.Rs self.BRs.question = self.Qs self.BRs.response_text = "Al año con fuerza" def testdatabase(self): all_database = Survey.objects.all() assert len(all_database) == 1 only_database = all_database[0] assert only_database == self.Sv
def test_save_modified_time(self): s = Survey(name='Survey') minute_slice = slice(0, 17) time = str(datetime.datetime.now()) s.save() saved_time = str(s.created_at) self.assertEqual(saved_time[minute_slice], time[minute_slice])
def deleteItem(): form = cgi.FieldStorage(); vote = form['voteon'].value; item = vote.replace("__"," "); survey = form['survey'].value; owner = users.get_current_user(); oldSurvey = db.GqlQuery("SELECT * FROM Survey WHERE name = :1 and owner = :2",survey,owner); oldValues = []; oldExpiration=""; for sur in oldSurvey: oldValues = sur.values; oldExpiration = sur.expiration; oldValues.remove(item); newSurvey = Survey(name=survey,owner=owner,values=oldValues,expiration=oldExpiration); db.delete(oldSurvey); newSurvey.put(); oldItem = db.GqlQuery("SELECT * FROM Item WHERE name = :1 and owner = :2 and survey = :3",item,owner,survey); db.delete(oldItem); oldSearch = db.GqlQuery("SELECT * FROM Search WHERE name = :1 and owner = :2 and survey = :3 and entityType = :4",item,owner,survey,"item"); db.delete(oldSearch); oldComment = db.GqlQuery("SELECT * FROM Comments WHERE itemName = :1 AND itemOwner = :2 AND survey = :3",item,owner,surveyName); db.delete(oldComment); oldCommentValidator = db.GqlQuery("SELECT * FROM CommentValidator WHERE itemName = :1 AND itemOwner = :2 AND survey = :3",item,owner,surveyName); db.delete(oldCommentValidator); oldVote = db.GqlQuery("SELECT * FROM Vote WHERE name = :1 AND owner = :2 AND survey = :3",item,owner,surveyName); db.delete(oldVote); return render_template('survey_confirmation.html',survey=survey,option=oldValues);
def new(request): response = None survey_form = SurveyForm() if request.method == 'POST': survey_form = SurveyForm(request.POST) if survey_form.is_valid(): Survey.save_sample_size(survey_form) messages.success(request, 'Survey successfully added.') response = HttpResponseRedirect(reverse('survey_list_page')) elif survey_form.errors.get('__all__'): messages.error(request, survey_form.errors['__all__']) context = { 'survey_form': survey_form, 'title': "New Survey", 'button_label': 'Create', 'id': 'add-survey-form', 'action': ".", 'cancel_url': request.META.get('HTTP_REFERER') or reverse('survey_list_page'), } request.breadcrumbs([ ('Surveys', reverse('survey_list_page')), ]) return response or render(request, 'surveys/new.html', context)
def edit(request, survey_id): try: survey = Survey.objects.get(id=survey_id) survey_form = SurveyForm(instance=survey) if request.method == 'POST': survey_form = SurveyForm(instance=survey, data=request.POST) if survey_form.is_valid(): Survey.save_sample_size(survey_form) messages.success(request, 'Survey successfully edited.') return HttpResponseRedirect(reverse('survey_list_page')) elif survey_form.errors.get('__all__'): messages.error(request, survey_form.errors['__all__']) context = {'survey_form': survey_form, 'title': "Edit Survey", 'button_label': 'Save', 'id': 'edit-survey-form', 'cancel_url': request.META.get('HTTP_REFERER') or reverse('survey_list_page'), 'action': reverse('edit_survey_page', args=(survey_id, )) } request.breadcrumbs([ ('Surveys', reverse('survey_list_page')), ]) return render(request, 'surveys/new.html', context) except Survey.DoesNotExist: messages.error(request, 'survey does not exists') return HttpResponseRedirect(reverse('survey_list_page'))
def edit(request, survey_id): try: survey = Survey.objects.get(id=survey_id) survey_form = SurveyForm(instance=survey) if request.method == 'POST': survey_form = SurveyForm(instance=survey, data=request.POST) if survey_form.is_valid(): Survey.save_sample_size(survey_form) messages.success(request, 'Survey successfully edited.') return HttpResponseRedirect(reverse('survey_list_page')) elif survey_form.errors.get('__all__'): messages.error(request, survey_form.errors['__all__']) context = { 'survey_form': survey_form, 'title': "Edit Survey", 'button_label': 'Save', 'id': 'edit-survey-form', 'cancel_url': request.META.get('HTTP_REFERER') or reverse('survey_list_page'), 'action': reverse('edit_survey_page', args=(survey_id, )) } request.breadcrumbs([ ('Surveys', reverse('survey_list_page')), ]) return render(request, 'surveys/new.html', context) except Survey.DoesNotExist: messages.error(request, 'survey does not exists') return HttpResponseRedirect(reverse('survey_list_page'))
def setUp(self): self.user = User.objects.get(username='******') # Survey_template model self.survey_template = Survey_template( name='test_survey', user=self.user, ) self.survey_template.save() # Survey model self.survey = Survey( name='test_survey', user=self.user, ) self.survey.save() self.assertEqual(self.survey.__unicode__(), u'test_survey') # Section_template self.section_template = Section_template.objects.get(pk=1) self.section_template.survey.name = 'New Survey' self.section_template.save() # Section model self.section = Section.objects.get(pk=1) self.section.save() self.assertTrue(self.section.__unicode__()) # Branching_template model self.branching_template = Branching_template( keys=5, section=self.section_template, ) self.branching_template.save() # Branching model self.branching = Branching( keys=5, section=self.section, ) self.branching.save() self.assertTrue(self.branching.__unicode__()) # Result model self.result = Result(section=self.section, callrequest_id=1, response='apple') self.result.save() self.assertEqual(self.result.__unicode__(), '[1] [1] call transfer = apple') # ResultAggregate model self.result_aggregate = ResultAggregate(survey=self.survey, section=self.section, count=1, response='apple') self.result_aggregate.save() self.assertEqual(self.result_aggregate.__unicode__(), '[1] [1] call transfer = apple')
def submit(request): if request.method == 'POST': s = Survey(data=request.raw_post_data, remote_addr=request.META["REMOTE_ADDR"], user_agent=request.META["HTTP_USER_AGENT"]) s.save() return HttpResponse("OK")
def submit(request): if request.method == 'POST': s = Survey(data = request.raw_post_data, remote_addr = request.META["REMOTE_ADDR"], user_agent = request.META["HTTP_USER_AGENT"]) s.save() return HttpResponse("OK")
def form(request, district_slug, school_slug, **kwargs): # check if district exists district = get_object_or_404(District.objects, slug__iexact=district_slug) # get school in district school = get_object_or_404(School.objects, districtid=district, slug__iexact=school_slug) # translate to lat/lon school.geometry.transform(4326) SurveyFormset = inlineformset_factory(Survey, Child, form=ChildForm, extra=1, can_delete=False) formerror = False if request.method == 'POST': surveyform = SurveyForm(request.POST, school=school) if surveyform.is_valid(): survey = surveyform.save(commit=False) survey.school = school survey.update_distance() survey.created = datetime.now() survey.ip = request.META['REMOTE_ADDR'] surveyformset = SurveyFormset(request.POST, instance=survey) if surveyformset.is_valid(): survey.save() surveyformset.save() return render_to_response( 'survey/thanks.html', context_instance=RequestContext(request)) else: surveyformset = SurveyFormset(request.POST, instance=Survey()) formerror = True else: surveyformset = SurveyFormset(request.POST, instance=Survey()) formerror = True else: survey = Survey() surveyform = SurveyForm(instance=survey) surveyformset = SurveyFormset(instance=survey) return render_to_response('survey/form.html', { 'formerror': formerror, 'school': school, 'surveyform': surveyform, 'surveyformset': surveyformset, }, context_instance=RequestContext(request))
def handle(self, *args, **options): # TODO: Remove or improve before production... logger.info('Deleting all surveys...') User.objects.filter(is_staff=False).delete() Survey.objects.all().delete() ChallengeDetail.objects.all().delete() logger.info('Starting import...') df = pd.read_excel(path.join(settings.BASE_DIR, 'respondents.xlsx'), sheetname='Delegates') df.fillna('', inplace=True) for idx, survey in df.iterrows(): data_raw = survey.to_dict() data = {k: str(v).strip() for k, v in data_raw.items()} try: country = Country.objects.get(name=data.get('country_of_operation')) data.update({'country_of_operation': country}) except Country.DoesNotExist: logger.warning('Could not find country %s' % data.get('country_of_operation')) data.update({'country_of_operation': None}) del data['countries'] # Create and associate user username = slugify(data.get('name')).replace('-', '_') slug = '{0}_{1}'.format(data.get('slug')[2:] or slug_generator(), username) logger.info(slug) user = User.objects.create_user(username[:30], data.get('email', ''), slug) survey = Survey(**data) survey.slug = slug survey.user = user survey.save() assign_perm('change_survey', user, obj=survey) # Creating challenges # for challenge in Challenge.objects.all(): # ChallengeDetail.objects.create(owner=slug, challenge=challenge) for rank in range(1, 4): ChallengeDetail.objects.create(respondent=survey, rank=rank) # try: # Survey(**data).save() # except IntegrityError: # logger.excep('Integ exisits: %s ' % data) # except: # logger.exception(data) # else: # for challenge in Challenge.objects.all(): # ChallengeDetail.objects.create(slug, challenge) logger.info('Done')
def handle(self, *args, **options): if Survey.objects.count() == 0: for s in SURVEY: survey = Survey(title=s['title'], published=s['published'], journeys=s['journeys']) survey.save() print('%s saved.' % (s['title'])) else: print('Survey table already initialized')
def login_user(request, slug): logger.info('Slug is: {}, trying to log in...'.format(slug)) request.session['survey_slug'] = slug request.session.save() survey_instance = None try: survey_instance = Survey.objects.get(slug=slug) except Survey.DoesNotExist: logger.info('Survey does not exist...') user = User(username=slug[30:]) user.set_password(slug) user.email = '' user.save() logger.info('Saved new user... {}'.format(user)) survey_instance = Survey(slug=slug, user=user) survey_instance.save() logger.info('Saved new survey... {}'.format(survey_instance)) for rank in range(1, 4): ChallengeDetail.objects.create(respondent=survey_instance, rank=rank) logger.info('Added new ChallengeDetail with respondent = {} and rank = {}'.format(survey_instance, rank)) else: logger.info('Found survey and use!:') finally: if request.user.is_staff: logger.info('Staff in the house!!') else: user = authenticate(username=survey_instance.user.username, password=slug) logger.info('Not staff, who is %s' % survey_instance.user.username) if user is not None: # If staff member is testing if user.is_active: logger.info('User is active!') login(request, user) # Redirect to a success page else: logger.warn('User not active') pass # Return a 'disabled account' error message else: logger.warn('Authentication Failed') pass # Return an 'invalid login' error message. # logger.info('Confirming that survey_slug is stored: {}'.format(request.session['survey_slug'])) return HttpResponseRedirect(reverse('survey:about'))
def post(self, request, *args, **kwargs): warnings = [] data = json.loads(request.POST.get('r')) title = data.get('title', '') slug = slugify(data.get('slug') or title) if not slug: warnings.append(_('Please enter a valid title.')) return HttpResponse(json.dumps({'status': 'failure', 'warnings': warnings}), mimetype='application/json') try: survey = self.get_object() if slug != survey.slug: warnings.append(_("This survey's URL has been changed. Be sure to update any QR code images.")) except AttributeError: survey = Survey(creator=request.user) survey.title = title survey.slug = slug survey.description = data.get('description', '') try: survey.save() except IntegrityError: warnings = [_('That title is already taken. Please choose a different one.')] return HttpResponse(json.dumps({'status': 'failure', 'warnings': warnings}), mimetype='application/json') # delete existing questions # due to cascading deletes, this will also delete choices QuestionGroup.objects.filter(pk__in=survey.question_set.all().values_list('group')).delete() survey.question_set.all().delete() questions = data.get('questions', []) groups = data.get('groups', []) survey.add_questions(questions, groups) return HttpResponse(json.dumps({'status': 'success', 'warnings': warnings, 'url': reverse('surveydashboard', args=[survey.slug])}), mimetype='application/json')
def __init__(self, *args, **kwargs): super(IndicatorForm, self).__init__(*args, **kwargs) if kwargs.get('instance'): qset = kwargs['instance'].question_set survey = kwargs['instance'].survey self.fields['survey'].initial = survey self.fields['survey'].widget.attrs['readonly'] = 'readonly' self.fields['question_set'].queryset = survey.qsets self.fields['question_set'].initial = qset self.fields['question_set'].widget.attrs['readonly'] = 'readonly' self.fields['variables'].initial = kwargs['instance'].variables.all() self.fields['variables'].queryset = self.available_variables() self.fields['variables'].icons = { 'add': { 'data-toggle': "modal", 'data-target': "#add_variable", 'id': 'add_new_variable', 'title': 'Add Variable'}, 'edit': { 'data-toggle': "modal", 'title': 'Edit Variable', 'id': 'edit_variable'}, 'delete': { 'data-toggle': "modal", 'data-target': "#remove-selected-variable", 'id': 'delete_variable', 'title': 'Delete Variable'}} self.fields['formulae'].icons = {'check': {'id': 'validate', 'title': 'Validate'}, } if self.data.get('survey'): self.fields['question_set'].queryset = Survey.get( pk=self.data['survey']).qsets self.fields['name'].label = 'Indicator' self.order_fields(['survey', 'question_set', 'name', 'description', 'variables', 'formulae'])
def stratification(request, option="AD"): piramid_list = {} task = Task() task.id = 1 task.survey = Survey() scales = task.get_scales(exclude='') for scale in scales: piramid_list[scale['name']] = [ [] for i in range(len(scale['scale']) + 1) ] filtered = request.GET.get('filter', '') if filtered == 'mine': patient_list = Profile.objects.filter(role=settings.PATIENT, doctor=request.user) else: patient_list = Profile.objects.filter(role=settings.PATIENT) for p in patient_list: for scale in scales: if not scale['scale']: scales.remove(scale) continue val = getattr(p, 'get_' + scale['hash'] + '_status')(index=True) if isinstance(val, int): piramid_list[scale['name']][val + 1].append(p) else: piramid_list[scale['name']][0].append(p) return render_to_response('statistic/stratification.html', {'piramid_list': piramid_list, 'scales': scales, 'filtered': filtered, 'num_patient': patient_list.count()}, context_instance=RequestContext(request))
def save(self, user, country, category, survey): survey = survey or Survey( user=user, country=country, category=category) for k, v in self.cleaned_data.items(): setattr(survey, k, v) survey.save() return survey
def get(self, request): from django.http import HttpResponse surveys = Survey.objects.all() temp = path(tempfile.mkdtemp()) filename = temp / 'survey.xls' wb = xlwt.Workbook() ws = wb.add_sheet('Survey') # adding columns columns = Survey.get_fields_for_serialization() for i, field in enumerate(columns): ws.write(0, i, capfirst(field.verbose_name)) # adding rows for i, survey in enumerate(surveys): for j, field in enumerate(columns): ws.write(i+1, j, survey.serialize_field(field)) wb.save(filename) # keep the file open until the download is finished # temp folder will be deleted after try: file_path = open(filename) finally: temp.rmtree() response = StreamingHttpResponse(self.read_file(file_path), content_type='application/xls') response['Content-Disposition'] = 'attachment; filename="survey.xls"' return response
def register(self, request, **kwargs): email, password = kwargs['email'], kwargs['password1'] username = email if Site._meta.installed: site = Site.objects.get_current() else: site = RequestSite(request) new_user = HtmlRegistrationProfile.objects.create_inactive_user( username, email, password, site) new_user.userprofile.survey = Survey() # if an anonymous user is registering, save their data if hasattr(request.user, 'userprofile'): if request.user.userprofile.is_anonymous: request.user.is_active = False request.user.save() survey = request.user.userprofile.survey survey.id = None survey.user_profile = new_user.userprofile survey.save() new_user.userprofile.survey = survey new_user.userprofile.survey.save() new_user.userprofile.allow_notifications = kwargs[ 'allow_notifications'] new_user.userprofile.save() signals.user_registered.send(sender=self.__class__, user=new_user, request=request) return new_user
def get_household_list(self, non_response_reporting=False): open_survey = Survey.currently_open_survey(self.investigator.location) page = self.get_from_session('PAGE') self.responseString += "%s\n%s" % ( self.MESSAGES['HOUSEHOLD_LIST'], self.investigator.households_list(page, registered=False, open_survey=open_survey, non_response_reporting=non_response_reporting))
def post(self, request, *args, **kwargs): warnings = [] data = json.loads(request.POST.get('r')) title = data.get('title', '') slug = slugify(data.get('slug') or title) if not slug: warnings.append(_('Please enter a valid title.')) return HttpResponse(json.dumps({ 'status': 'failure', 'warnings': warnings }), mimetype='application/json') try: survey = self.get_object() if slug != survey.slug: warnings.append( _("This survey's URL has been changed. Be sure to update any QR code images." )) except AttributeError: survey = Survey(creator=request.user) survey.title = title survey.slug = slug survey.description = data.get('description', '') try: survey.save() except IntegrityError: warnings = [ _('That title is already taken. Please choose a different one.' ) ] return HttpResponse(json.dumps({ 'status': 'failure', 'warnings': warnings }), mimetype='application/json') # delete existing questions # due to cascading deletes, this will also delete choices QuestionGroup.objects.filter( pk__in=survey.question_set.all().values_list('group')).delete() survey.question_set.all().delete() questions = data.get('questions', []) groups = data.get('groups', []) survey.add_questions(questions, groups) return HttpResponse(json.dumps({ 'status': 'success', 'warnings': warnings, 'url': reverse('surveydashboard', args=[survey.slug]) }), mimetype='application/json')
def wipe_survey_data(request, survey_id): from survey.models import Interview from survey.utils import views_helper if views_helper.has_super_powers(request): survey = Survey.get(pk=survey_id) Interview.objects.filter(survey=survey).delete() messages.info(request, 'Data has been cleared for %s' % survey.name) return HttpResponseRedirect(reverse('survey_list_page'))
def list_qsets(request): if request.GET.get('survey_id'): values = Survey.get(id=request.GET.get('survey_id')).qsets.values( 'id', 'name') else: values = QuestionSet.objects.values('id', 'name') return HttpResponse(json.dumps(list(values)), content_type='application/json')
def select_household(self, answer, non_response_reporting=False): try: answer = int(answer) open_survey = Survey.currently_open_survey(self.investigator.location) self.household = self.investigator.all_households(open_survey, non_response_reporting)[answer - 1] self.set_in_session('HOUSEHOLD', self.household) except (ValueError, IndexError) as e: self.responseString += "INVALID SELECTION: "
def setUp(self): self.Sv = Survey() self.Sv.name = "Plantas" self.Sv.description = "ya jale todo" self.Sv.save() self.Qs = Question() self.Qs.question_text = "¿es GG?" self.Qs.survey = self.Sv self.Rs = Response() self.name = "Carlos" self.survey = self.Sv self.BRs = BaseResponse() self.BRs.response = self.Rs self.BRs.question = self.Qs self.BRs.response_text = "Al año con fuerza"
def render_homepage(self): open_survey = Survey.currently_open_survey(self.investigator.location) answer = self.request['ussdRequestString'].strip() if not self.investigator.has_households(survey=open_survey): self.action = self.ACTIONS['END'] self.responseString = self.MESSAGES['NO_HOUSEHOLDS'] else: self.render_household_or_household_member(answer, open_survey)
def save(self, user, country, category, survey): survey = survey or Survey( user=user, country=country, category=category, ) survey.section_a_comment = self.cleaned_data['comment'] survey.save() return survey
def load_data(apps, schema_editor): model_survey = apps.get_model("survey", "Survey") for survey in model_survey.objects.all(): # update survey survey.code = Survey.create_random_survey_code() survey.save()
def set_household_form(uid=None, data=None, is_edit=False, instance=None): household_form = {} if not is_edit: household_form['householdHead'] = HouseholdHeadForm(data=data, auto_id='household-%s', label_suffix='') open_survey = Survey.currently_open_survey() household_form['household'] = HouseholdForm(data=data, instance=instance, is_edit=is_edit, uid=uid, survey=open_survey, auto_id='household-%s', label_suffix='') return household_form
def list_qsets(request): if request.GET.get('survey_id'): values = Survey.get( id=request.GET.get('survey_id')).qsets.values( 'id', 'name') else: values = QuestionSet.objects.values('id', 'name') return HttpResponse( json.dumps( list(values)), content_type='application/json')
def save(self, user, country, category, survey): language = Language.objects.get(pk=self.cleaned_data['language']) survey = survey or Survey( user=user, country=country, category=category) for k, v in self.cleaned_data.items(): if k == 'language': setattr(survey, k, language) else: setattr(survey, k, v) survey.save() return survey
def addItems(): form = cgi.FieldStorage(); user = users.get_current_user(); sName = form['addon'].value; sName1 = sName.split(" by "); sName2 = sName1[0]; surveyName = sName2.replace("__"," "); rawOptions = form['additems'].value; rawOptions += ','; optionList = rawOptions.split(','); counter = 0; for option in optionList: itemPresent = db.GqlQuery("SELECT * FROM Item WHERE name = :1 AND survey = :2 and owner = :3",option,surveyName,user); counter1 = itemPresent.count(); if (counter1 > 0): counter = counter + 1; if (counter > 0): return render_template('failure.html',message="One or more items that you tried to add are already present in this category.None of the items were added."); else: surveys = db.GqlQuery("SELECT * FROM Survey WHERE name = :1 and owner = :2",surveyName,user); oldItemList = []; oldExpiration =""; for sur in surveys: if (sur.name == surveyName): oldItemList = sur.values; oldExpiration = sur.expiration; for newItems in optionList: oldItemList.append(newItems); newItemList = oldItemList; db.delete(surveys); newSurvey = Survey(name=surveyName,owner=user,values=newItemList,expiration=oldExpiration); newSurvey.put(); for option in optionList: if option: item = Item(name=option); item.survey = surveyName; item.owner = user; search1 = Search(name=option,entityType="item",survey=surveyName,owner=user); item.put(); search1.put(); return render_template('survey_confirmation.html',survey=surveyName,option=optionList);
def addSurvey(): form = cgi.FieldStorage(); user = users.get_current_user(); surveyName = form['sname'].value.strip(); rawOptions = form['options'].value; rawOptions += ','; optionList = rawOptions.split(','); surveyExpireDate = ""; if (form.has_key("dateValue")): expireDate = form['dateValue'].value; expireHour = int(form['hours'].value); expireMinutes = int(form['minutes'].value); expireSeconds = int(form['seconds'].value); rawDate = expireDate.split("/"); month = int(rawDate[0]); day = int(rawDate[1]); year = int(rawDate[2]); surveyExpireDate = datetime.datetime(year,month,day,expireHour,expireMinutes,expireSeconds); else: surveyExpireDate = datetime.datetime(2012,12,30,0,0,0); surveys = db.GqlQuery("SELECT * FROM Survey WHERE name = :1 and owner = :2",surveyName,user); counter = surveys.count(); if (counter == 0): survey = Survey(name=surveyName,expiration=surveyExpireDate); survey.values = optionList; survey.owner = user; survey.put(); search = Search(name=surveyName,entityType="survey",survey=surveyName,owner=user); search.put(); for option in optionList: if option: item = Item(name=option); item.survey = surveyName; item.owner = user; item.put(); search1 = Search(name=option,entityType="item",survey=surveyName,owner=user); search1.put(); return render_template('survey_confirmation.html',survey=surveyName,option=optionList); else: return render_template('failure.html',message="You already have created this survey! Please create a different survey.");
def renameCategory(): form = cgi.FieldStorage(); user = users.get_current_user(); newSurveyName = form['renameText'].value.strip(); oldSurveyName = form['renamesurvey'].value; newNameCheck = db.GqlQuery("SELECT * FROM Survey WHERE owner = :1 AND name = :2",user,newSurveyName); counter = newNameCheck.count(); if (counter > 0): return render_template('failure.html',message="You already have a survey with given name. Please try with some other name"); else: oldSurvey = db.GqlQuery("SELECT * FROM Survey WHERE owner = :1 AND name = :2",user,oldSurveyName); for old in oldSurvey: newSurvey = Survey(name=newSurveyName,values=old.values,owner=old.owner,expiration=old.expiration); newSurvey.put(); oldItems = db.GqlQuery("SELECT * FROM Item WHERE survey = :1 and owner = :2",oldSurveyName,user); for old in oldItems: newItem = Item(name=old.name,image=old.image,survey=newSurveyName,owner=old.owner); newItem.put(); oldVotes = db.GqlQuery("SELECT * FROM Vote WHERE survey = :1 and owner = :2",oldSurveyName,user); for old in oldVotes: newVote = Vote(name=old.name,owner=old.owner,win=old.win,survey=newSurveyName); newVote.put(); oldComments = db.GqlQuery("SELECT * FROM Comments WHERE itemOwner = :1 AND survey = :2",user,oldSurveyName); for old in oldComments: newComment = Comments(itemName=old.itemName,itemOwner=old.itemOwner,comment=old.comment,survey=newSurveyName); newComment.put(); oldCommentValidator = db.GqlQuery("SELECT * FROM CommentValidator where itemOwner = :1 and survey = :2",user,oldSurveyName); for old in oldCommentValidator: newCommentValidator = CommentValidator(itemName=old.itemName,itemOwner=old.itemOwner,commenter=old.commenter,survey=newSurveyName); newCommentValidator.put(); oldSearch = db.GqlQuery("SELECT * FROM Search WHERE survey = :1 AND owner = :2",oldSurveyName,user); for old in oldSearch: if(old.entityType == "survey"): newSearch = Search(name=newSurveyName,entityType=old.entityType,survey=newSurveyName,owner=old.owner); newSearch.put(); else: newSearch = Search(name=old.name,entityType=old.entityType,survey=newSurveyName,owner=old.owner); newSearch.put(); deleteGeneric(surveyName=oldSurveyName); return render_template('failure.html',message="Update Successful!");
def save_survey(self, survey_id, survey_unique_value, status, user_comment, internal_comment, created_at, updated_at): self.surveys.append( Survey( id=int(survey_id), survey_unique_value=survey_unique_value, status=int(status), user_comment=user_comment, internal_comment=internal_comment, created_at=created_at, updated_at=updated_at, ))
def index(request, survey_id=None): if survey_id: survey = Survey.get(pk=survey_id) request.breadcrumbs(Batch.index_breadcrumbs(survey=survey)) if survey_id is None: batches = Batch.objects.all() else: batches = Batch.objects.filter(survey__id=survey_id) qset_view = QuestionSetView(model_class=Batch) qset_view.questionSetForm = BatchForm return qset_view.index( request, batches, extra_context={ 'survey': survey}, initial={ 'survey': survey.pk})
def index(request, survey_id=None): if survey_id: survey = Survey.get(pk=survey_id) request.breadcrumbs(Batch.index_breadcrumbs(survey=survey)) if survey_id is None: batches = Batch.objects.all() else: batches = Batch.objects.filter(survey__id=survey_id) qset_view = QuestionSetView(model_class=Batch) qset_view.questionSetForm = BatchForm return qset_view.index(request, batches, extra_context={'survey': survey}, initial={'survey': survey.pk})
def create_survey(request): if request.POST: survey_title = request.POST.get("survey_title") survey_description = request.POST.get("survey_description") if survey_title == "New Survey(Click to change)": survey_title = "No title" if survey_description == "Add description here" or survey_description == "Click here to add...": survey_description = "" publishBool = request.POST.get("publishBool") survey = Survey(title=survey_title) survey.description = survey_description creator = User.objects.get(id = int(request.POST.get( "creatorID"))) survey.user = creator survey.theme_name = request.POST.get("theme_name") deadline = request.POST.get("survey_deadline") survey.deadline = datetime.strptime(deadline.strip(), "%d/%m/%Y") survey.save() collaborators = request.POST.get("collaborators") collaborators = collaborators.split(",") try: collaborators.remove("") except BaseException as e: pass for collaborator_id in collaborators: collaboration = Collaboration() collaboration.user = User.objects.get(id = int(collaborator_id)) collaboration.survey = survey collaboration.is_active = True collaboration.save() if publishBool == 'true': survey.is_published = True survey.save() surveyID = survey.id dict = {"surveyID": surveyID, "survey_key": survey.key} return HttpResponse(simplejson.dumps(dict), mimetype='application/javascript') return error_jump(request)
def restart_survey(self): answer = self.request['ussdRequestString'].strip() if answer == self.ANSWER['YES']: if self.has_chosen_household_member(): self.household_member.mark_past_answers_as_old() self.render_survey() else: self.render_household_members_list() if answer == self.ANSWER['NO']: self.set_in_session('HOUSEHOLD', None) self.set_in_session('HOUSEHOLD_MEMBER', None) self.household = None self.render_households_list(Survey.currently_open_survey(self.investigator.location)) self.action = self.ACTIONS['REQUEST']
def new(request): response = None survey_form = SurveyForm() if request.method == 'POST': survey_form = SurveyForm(request.POST) if survey_form.is_valid(): Survey.save_sample_size(survey_form) messages.success(request, 'Survey successfully added.') response = HttpResponseRedirect(reverse('survey_list_page') ) elif survey_form.errors.get('__all__'): messages.error(request, survey_form.errors['__all__']) context = {'survey_form': survey_form, 'title': "New Survey", 'button_label': 'Create', 'id': 'add-survey-form', 'action': ".", 'cancel_url': request.META.get('HTTP_REFERER') or reverse('survey_list_page'), } request.breadcrumbs([ ('Surveys', reverse('survey_list_page')), ]) return response or render(request, 'surveys/new.html', context)
def updateExpiration(): form = cgi.FieldStorage(); user = users.get_current_user(); oldSurveyName = form['update'].value; surveyExpireDate = ""; if (form.has_key("dateValue")): expireDate = form['dateValue'].value; expireHour = int(form['hours'].value); expireMinutes = int(form['minutes'].value); expireSeconds = int(form['seconds'].value); rawDate = expireDate.split("/"); month = int(rawDate[0]); day = int(rawDate[1]); year = int(rawDate[2]); surveyExpireDate = datetime.datetime(year,month,day,expireHour,expireMinutes,expireSeconds); else: surveyExpireDate = datetime.datetime(2012,12,30,0,0,0); oldSurvey = db.GqlQuery("SELECT * FROM Survey WHERE name = :1 AND owner = :2",oldSurveyName,user); newSurvey=""; for old in oldSurvey: newSurvey= Survey(name=old.name,values=old.values,owner=old.owner,expiration=surveyExpireDate); db.delete(oldSurvey); newSurvey.put(); return render_template('failure.html',message="Update Successful.");
def restart_survey(self): answer = self.request['ussdRequestString'].strip() if answer == self.ANSWER['YES']: if self.has_chosen_household_member(): self.household_member.mark_past_answers_as_old() self.render_survey() else: self.render_household_members_list() if answer == self.ANSWER['NO']: self.set_in_session('HOUSEHOLD', None) self.set_in_session('HOUSEHOLD_MEMBER', None) self.household = None self.render_households_list( Survey.currently_open_survey(self.investigator.location)) self.action = self.ACTIONS['REQUEST']
def __init__(self, *args, **kwargs): super(IndicatorForm, self).__init__(*args, **kwargs) if kwargs.get('instance'): qset = kwargs['instance'].question_set survey = kwargs['instance'].survey self.fields['survey'].initial = survey self.fields['survey'].widget.attrs['readonly'] = 'readonly' self.fields['question_set'].queryset = survey.qsets self.fields['question_set'].initial = qset self.fields['question_set'].widget.attrs['readonly'] = 'readonly' self.fields['variables'].initial = kwargs[ 'instance'].variables.all() self.fields['variables'].queryset = self.available_variables() self.fields['variables'].icons = { 'add': { 'data-toggle': "modal", 'data-target': "#add_variable", 'id': 'add_new_variable', 'title': 'Add Variable' }, 'edit': { 'data-toggle': "modal", 'title': 'Edit Variable', 'id': 'edit_variable' }, 'delete': { 'data-toggle': "modal", 'data-target': "#remove-selected-variable", 'id': 'delete_variable', 'title': 'Delete Variable' } } self.fields['formulae'].icons = { 'check': { 'id': 'validate', 'title': 'Validate' }, } if self.data.get('survey'): self.fields['question_set'].queryset = Survey.get( pk=self.data['survey']).qsets self.fields['name'].label = 'Indicator' self.order_fields([ 'survey', 'question_set', 'name', 'description', 'variables', 'formulae' ])
def create_household(householdform, investigator, valid, uid): is_valid_household = householdform['household'].is_valid() if investigator and is_valid_household: household = householdform['household'].save(commit=False) household.investigator = investigator household.ea = investigator.ea open_survey = Survey.currently_open_survey(investigator.location) household.household_code = LocationCode.get_household_code(investigator) + str(Household.next_uid(open_survey)) if uid: household.uid = uid household.household_code = LocationCode.get_household_code(investigator) + str(uid) household.survey = open_survey household.save() valid['household'] = True return valid
def _update_survey_data(self): """Make dummy references to limesurvey surveys until import them in Limesurvey. Create new survey codes """ next_code = Survey.create_random_survey_code() indexes = [index for index, dict_ in enumerate(self.data) if dict_['model'] == 'survey.survey'] if indexes: min_limesurvey_id = Survey.objects.order_by('lime_survey_id')[0].lime_survey_id if min_limesurvey_id >= 0: dummy_limesurvey_id = -99 else: # TODO (NES-956): testar isso dummy_limesurvey_id = min_limesurvey_id - 1 for index in indexes: self.limesurvey_relations[self.data[index]['fields']['lime_survey_id']] = dummy_limesurvey_id self.data[index]['fields']['lime_survey_id'] = dummy_limesurvey_id dummy_limesurvey_id -= 1 next_code = 'Q' + str(int(next_code.split('Q')[1]) + 1) self.data[index]['fields']['code'] = next_code
def _update_survey_stuff(self): indexes = [index for (index, dict_) in enumerate(self.data) if dict_['model'] == 'survey.survey'] if indexes: # Update survey codes next_code = Survey.create_random_survey_code() # Update lime survey ids min_limesurvey_id = Survey.objects.all().order_by('lime_survey_id')[0].lime_survey_id \ if Survey.objects.count() > 0 else 0 if min_limesurvey_id >= 0: new_limesurvey_id = -99 else: new_limesurvey_id = min_limesurvey_id for i in indexes: self.data[i]['fields']['code'] = next_code next_code = 'Q' + str(int(next_code.split('Q')[1]) + 1) new_limesurvey_id -= 1 self.data[i]['fields']['lime_survey_id'] = new_limesurvey_id
def handle(self, *args, **kwargs): """Basically loads each line of the csv as9 responses to the question set each row is seen as a seperate interview.9 first field would be the ea ID, subsequent fields would be the answers9 :param args: :param kwargs: :return: """ self.stdout.write('Starting...') delimiter = kwargs.get('delim', ',') df = pd.read_csv(args[0], delimiter=delimiter) interviewer = Interviewer.get(pk=args[1]) survey = Survey.get(pk=args[2]) qset = QuestionSet.get(pk=int(args[3])) odk_access = interviewer.odk_access[0] all_questions = qset.all_questions eas = {} #>with transaction.atomic(): df.apply(save_interview, axis=1, args=(interviewer, odk_access, survey, qset, all_questions, eas)) self.stdout.write('Successfully imported!')
def households_for_open_survey(interviewer): open_survey = Survey.currently_open_surveys(interviewer.location) households = interviewer.households.filter(survey__in=open_survey).all() return len([hs for hs in households if hs.get_head() is not None])
def setUp(self): self.user = User.objects.get(username='******') # Survey_template model self.survey_template = Survey_template( name='test_survey', user=self.user, ) self.survey_template.save() # Survey model self.survey = Survey( name='test_survey', user=self.user, ) self.survey.save() self.assertEqual(self.survey.__unicode__(), u'test_survey') # Section_template self.section_template = Section_template.objects.get(pk=1) self.section_template.survey.name = 'New Survey' self.section_template.save() # Section model self.section = Section.objects.get(pk=1) self.section.save() self.assertTrue(self.section.__unicode__()) # Branching_template model self.branching_template = Branching_template( keys=5, section=self.section_template, ) self.branching_template.save() # Branching model self.branching = Branching( keys=5, section=self.section, ) self.branching.save() self.assertTrue(self.branching.__unicode__()) # Result model self.result = Result( section=self.section, callrequest_id=1, response='apple' ) self.result.save() self.assertEqual( self.result.__unicode__(), '[1] [1] call transfer = apple') # ResultAggregate model self.result_aggregate = ResultAggregate( survey=self.survey, section=self.section, count=1, response='apple' ) self.result_aggregate.save() self.assertEqual( self.result_aggregate.__unicode__(), '[1] [1] call transfer = apple')
class SurveyModel(TestCase): """Test Survey, Section, Branching, Result, ResultAggregate Model""" fixtures = ['auth_user.json', 'gateway.json', 'dialer_setting.json', 'user_profile.json', # 'contenttype.json', 'phonebook.json', 'contact.json', 'dnc_list.json', 'dnc_contact.json', 'campaign.json', 'subscriber.json', 'callrequest.json', 'voipcall.json', 'survey_template.json', 'survey.json', 'section_template.json', 'section.json', 'branching.json', ] def setUp(self): self.user = User.objects.get(username='******') # Survey_template model self.survey_template = Survey_template( name='test_survey', user=self.user, ) self.survey_template.save() # Survey model self.survey = Survey( name='test_survey', user=self.user, ) self.survey.save() self.assertEqual(self.survey.__unicode__(), u'test_survey') # Section_template self.section_template = Section_template.objects.get(pk=1) self.section_template.survey.name = 'New Survey' self.section_template.save() # Section model self.section = Section.objects.get(pk=1) self.section.save() self.assertTrue(self.section.__unicode__()) # Branching_template model self.branching_template = Branching_template( keys=5, section=self.section_template, ) self.branching_template.save() # Branching model self.branching = Branching( keys=5, section=self.section, ) self.branching.save() self.assertTrue(self.branching.__unicode__()) # Result model self.result = Result( section=self.section, callrequest_id=1, response='apple' ) self.result.save() self.assertEqual( self.result.__unicode__(), '[1] [1] call transfer = apple') # ResultAggregate model self.result_aggregate = ResultAggregate( survey=self.survey, section=self.section, count=1, response='apple' ) self.result_aggregate.save() self.assertEqual( self.result_aggregate.__unicode__(), '[1] [1] call transfer = apple') def test_survey_forms(self): self.assertEqual(self.survey_template.name, "test_survey") #self.assertEqual(self.section_template.survey, self.survey_template) self.assertEqual(self.branching_template.section, self.section_template) self.assertEqual(self.result.section, self.section) form = PlayMessageSectionForm(self.user, instance=self.section_template) obj = form.save(commit=False) obj.question = "test question" obj.type = 1 obj.survey = self.survey_template obj.save() form = MultipleChoiceSectionForm(self.user, instance=self.section_template) obj = form.save(commit=False) obj.type = 2 obj.question = "test question" obj.key_0 = "apple" obj.survey = self.survey_template obj.save() form = RatingSectionForm(self.user, instance=self.section_template) obj = form.save(commit=False) obj.type = 3 obj.question = "test question" obj.rating_laps = 5 obj.survey_template = self.survey_template obj.save() form = CaptureDigitsSectionForm(self.user, instance=self.section_template) obj = form.save(commit=False) obj.type = 4 obj.question = "test question" obj.number_digits = 2 obj.min_number = 1 obj.max_number = 100 obj.survey = self.survey_template obj.save() form = RecordMessageSectionForm(self.user) obj = form.save(commit=False) obj.type = 5 obj.question = "test question" obj.survey = self.survey_template obj.save() form = CallTransferSectionForm(self.user) obj = form.save(commit=False) obj.type = 6 obj.question = "test question" obj.phonenumber = 1234567890 obj.survey = self.survey_template obj.save() form = SMSSectionForm(self.user) obj = form.save(commit=False) obj.type = 10 obj.question = "sms question" obj.sms_text = "this is test sms" obj.survey = self.survey_template obj.save() form = ScriptForm() obj = form.save(commit=False) obj.script = 'xyz' obj.survey = self.survey_template obj.save() form = SurveyDetailReportForm(self.user) def teardown(self): self.survey_template.delete() self.survey.delete() self.section_template.delete() self.section.delete() self.branching_template.delete() self.branching.delete() self.result.delete() self.result_aggregate.delete()
def is_active(self): return self.investigator.was_active_within(self.TIMEOUT_MINUTES) or self.investigator.created_member_within( self.TIMEOUT_MINUTES, Survey.currently_open_survey(self.investigator.location))
def buildSurvey(user,phone_number): print "build survey" thedatetime = datetime.datetime.now().strftime("%Y:%m:%d:%H:%M:%S") title = str(phone_number) + "/" + thedatetime survey = Survey(title = title) survey.save() textmessagelist = [] for conver in user.sms_conversation_set.all(): for message in conver.sms_message_set.all(): if message.from_last_day(): textmessagelist.append(" recipient: " + message.recipient) textmessagelist.append("\t message: " + decrypt(key,message.SmSbody)) facemessagelist = [] for faceConver in user.facebook_conversation_set.all(): for faceMessage in faceConver.facebook_messages_set.all(): if faceMessage.from_last_day(): facemessagelist.append(" text: " + decrypt(key,faceMessage.body)) faceactlist = [] faceComm = [] for faceact in user.facebook_activity_set.all(): if faceact.from_last_day(): try: md = decrypt(key, faceact.message) except Exception as e: print e fmsg = faceact.message #print "new facebook key=[%s] orig=[%s] decrypt=[%s, %d]" % (key, faceact.message, md, len(md)) if decrypt(key,faceact.message): faceactlist.append(" activity:" + decrypt(key,faceact.message)) #print "added activity", len(faceactlist) else: #print "no activity. decrypt failed?" pass for com in faceact.facebook_comments_set.all(): if decrypt(key,com.text): faceComm.append(" comment:" + decrypt(key,com.text)) twitterStatus = [] qs = list(twitter_status.objects.filter(author = user)) for twitterstatus in qs: if twitterstatus.from_last_day(): twitterStatus.append(" twitter status :" + twitterstatus.body + "\n") print(textmessagelist) if not textmessagelist: textmessagelist.append("No text messages sent in last day") text = "Text messages from last day: \n" + "\n".join(textmessagelist) q1 = survey.question_set.create(text = text,atype=1) y1 = q1.choice_set.create(choice_text="Yes") n1 = q1.choice_set.create(choice_text="No") print(facemessagelist) if not facemessagelist: facemessagelist.append("No facebook instant massages from last day") text2 = "Facebook message from last day: \n" + "\n".join(facemessagelist)+ "\n".join(faceComm) q2 = survey.question_set.create(text = text2,atype=1) y2 = q2.choice_set.create(choice_text="Yes") n2 = q2.choice_set.create(choice_text="No") print("activity list %s %d", str(faceactlist), len(faceactlist)) if not faceactlist: faceactlist.append("No facebook activities from last day") text4 = "Facebook activities from last day: \n" + "\n".join(faceactlist) q4 = survey.question_set.create(text = text4,atype=1) y4 = q4.choice_set.create(choice_text="Yes") n4 = q4.choice_set.create(choice_text="No") if not twitterStatus: twitterStatus.append("No new twitter status") text3 = "Twitter status from last day: \n" + "\n".join(twitterStatus) q3 = survey.question_set.create(text = text3,atype=1) y3 = q3.choice_set.create(choice_text="Yes") n3 = q3.choice_set.create(choice_text="No") return survey