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 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 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 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 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 populate(): print('Populating Survey and Question ... ', end='') Survey.objects.all().delete() Question.objects.all().delete() Choice.objects.all().delete() Response.objects.all().delete() userList = User.objects.first() for title in titles: survey = Survey() survey.title = title survey.description = title survey.date = datetime.date.today() survey.startDate = survey.date survey.endDate = survey.startDate + datetime.timedelta(60) survey.user = userList survey.emailContent = '新的問題開始' survey.save() for content in contents: question = Question() question.survey = survey question.title += 'Q:' + title question.description += title + content + '\n' question.save() Choice.objects.create(question=question, name='是') Choice.objects.create(question=question, name='否,另有要事') print('done')
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 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 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 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 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 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 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 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)
while not question_done: try: limit = int (raw_input (' Character limit: ') ) question_done = True except: print ('Enter an integer') survey['questions'].append ( {'type': 'text', 'text': question_text, 'character_limit': limit} ) question_num = question_num + 1 print ('') else: survey_done = True if len (survey['questions']) > 0 and len (survey['groups']) > 0: # now the survey can be saved in the database survey_obj = Survey (survey['title'], datetime.now (), None, None) mysql.add (survey_obj) for g in survey['groups']: survey_obj.groups.append (group) mysql.flush () for q in survey['questions']: if q['type'] == 'choice': question = ChoiceQuestion (q['text'], survey_obj.id) survey_obj.questions.append (question) mysql.flush () for c in q['choices']: choice = Choice (c, question.id)
def publish_new_survey(request): password = request.POST.get('password') return_data = {} if not request.user.check_password(password): return_data['STATUS'] = '0' return_data['MESSAGE'] = 'Wrong password' else: survey_title = request.POST.get('surveyTitle') survey_description = request.POST.get('surveyDescription') survey_content = json.loads(request.POST.get('surveyContent')) survey = Survey() survey.survey_title = survey_title survey.survey_desc = survey_description survey.aspirant = Client.objects.get(user=request.user) return_data['MESSAGE'] = [] try: survey.save() return_data['MESSAGE'].append({ 'STATUS': '1', 'MESSAGE': 'Survey has been created.' }) for content in survey_content: survey_question = SurveyQuestion() survey_question.survey = survey survey_question.question_number = content['question_number'] survey_question.question = content['question'] try: survey_question.save() return_data['MESSAGE'].append({ 'STATUS': '1', 'MESSAGE': "'{}' survey question has been added.".format(content['question']) }) options_list = content['option'].split('#') for option in options_list: try: survey_options = SurveyOptions() survey_options.option = option survey_options.survey_question = survey_question survey_options.save() return_data['MESSAGE'].append({ 'STATUS': '1', 'MESSAGE': "'{}' survey option has been added.".format(option) }) except Exception as ex: return_data['MESSAGE'].append({ 'STATUS': '0', 'MESSAGE': "'{}' survey option failed to be added. Error: {}".format(option, str(ex)) }) except Exception as ex: return_data['MESSAGE'].append({ 'STATUS': '0', 'MESSAGE': "'{}' survey question failed to be added. Error: ".format(content['question'], str(ex)) }) subscriber_filter = json.loads(request.POST.get('subscriber_filter')) subscriber_filter['user'] = request.user try: sms_utils = SmsUtil() subscribers = sms_utils.filter_sms_recipients(subscriber_filter) for subscriber in subscribers: survey_recipient = SurveyRecipient( survey=survey, subscriber=subscriber) survey_recipient.save() except Exception as exe: print(str(exe)) pass except Exception as ex: return_data['MESSAGE'].append({ 'STATUS': '0', 'MESSAGE': 'Survey failed to be created. Error: '.format(str(ex)) }) return HttpResponse(json.dumps(return_data))
def post(self, request): # save the new survey to database userid = request.query_params['userid'] survey = Survey(data=request.data, creator_id=userid) survey.save() return HttpResponse(status.HTTP_201_CREATED)
def batch_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 message = "New survey" if request.method == 'POST': surveyform = BatchForm(request.POST, school=school) if surveyform.is_valid(): survey = surveyform.save(commit=False) # Ugly Fix: created should save to model, but does not! created = surveyform.cleaned_data['created'] survey.created = created survey.user = request.user survey.school = school survey.update_distance() if survey.location is None or survey.location.x == 0: survey.update_location() survey.ip = request.META['REMOTE_ADDR'] surveyformset = SurveyFormset(request.POST, instance=survey) if surveyformset.is_valid(): survey.save() surveyformset.save() #Done. Make new form. message = "Survey submitted. New Entry." #Save created to reduce repeating survey = Survey(created=created) surveyform = BatchForm(instance=survey, initial={'created': created}) surveyformset = SurveyFormset(instance=survey) else: surveyformset = SurveyFormset(request.POST, instance=Survey(created=created)) formerror = True else: surveyformset = SurveyFormset(request.POST, instance=Survey()) formerror = True else: survey = Survey() surveyform = BatchForm(instance=survey) surveyformset = SurveyFormset(instance=survey) return render_to_response('survey/batch.html', { 'message': message, 'formerror': formerror, 'school': school, 'surveyform': surveyform, 'surveyformset': surveyformset, }, context_instance=RequestContext(request))
def save_survey(request, surveyID): if request.POST: question_type = request.POST.get("question_type") question_no = request.POST.get("question_no") question_helptext = request.POST.get("question_helptext") is_required = request.POST.get("is_required") if question_helptext == "Click here to add...": question_helptext == "" question_title = request.POST.get("question_title") selections = request.POST.get("selections") attributes = request.POST.get("attributes") if int(surveyID) == 0: survey = Survey(title="no title") survey.save() surveyID = survey.id if question_type == "paragraph": question = ParagraphQuestion() elif question_type == "numeric": question = NumericQuestion() elif question_type == "multiplechoice": question = MultipleChoiceQuestion() elif question_type == "checkbox": question = CheckboxQuestion() elif question_type == "scale": question = ScaleQuestion() elif question_type == "text": question = TextQuestion() elif question_type == "date": question = DateQuestion() else: return question.survey = Survey.objects.get(id=surveyID) question.id_in_survey = question_no question.title = question_title.strip() question.help_text = question_helptext question.max_no_characters = 0 if is_required == 'true': question.is_required = True else: question.is_required = False question.save() if question_type == "paragraph": attributes_list = attributes.split("@#@") question.max_no_characters = int(attributes_list[0]) elif question_type == "numeric": attributes_list = attributes.split("@#@") question.max_value = float(attributes_list[0]) question.min_value = float(attributes_list[1]) elif question_type == "multiplechoice": choices = selections.split("@#@") choices.pop() count = 0 for choice_label in choices: count += 1 choice = MultipleChoice() choice.question = question choice.label = choice_label choice.id_in_question = count choice.save() elif question_type == "checkbox": attributes_list = attributes.split("@#@") question.max_checked = int(attributes_list[0]) question.min_checked = int(attributes_list[1]) choices = selections.split("@#@") choices.pop() count = 0 for choice_label in choices: count += 1 choice = CheckboxChoice() choice.question = question choice.label = choice_label choice.id_in_question = count choice.save() elif question_type == "scale": attributes_list = attributes.split("@#@") question.max_value = float(attributes_list[0]) question.min_value = float(attributes_list[1]) question.increment = float(attributes_list[2]) elif question_type == "date": attributes_list = attributes.split("@#@") question.min_value = datetime.strptime(attributes_list[0].strip(),"%d/%m/%Y") question.max_value = datetime.strptime(attributes_list[1].strip(),"%d/%m/%Y") question.start_value = datetime.strptime(attributes_list[2].strip(),"%d/%m/%Y") elif question_type == "text": attributes_list = attributes.split("@#@") question.max_no_characters = int(attributes_list[0]) else: return question.save() dict = {"surveyID": surveyID} return HttpResponse(simplejson.dumps(dict), mimetype='application/javascript') return error_jump(request)
def add_survey(survey_file_path, survey_anime_file_path, survey_late_adds_file_path, year, quarter, is_preseason): survey_queryset = Survey.objects.filter(year=year, season=quarter, is_preseason=is_preseason) if len(survey_queryset) > 0: survey = survey_queryset[0] print('Found pre-existing survey: "%s"' % str(survey)) answer = input('Delete this survey and continue? (Y/N)').lower() while answer != 'y' and answer != 'n': answer = input('Delete this survey and continue? (Y/N)').lower() if answer == 'n': return deletion_count, deletion_dict = Response.objects.filter(survey=survey).delete() print('Deleted %i responses: %s' % (deletion_count, str(deletion_dict))) else: survey = Survey( year=year, season=quarter, is_preseason=is_preseason, is_ongoing=False, ) survey.save() print('Created a new survey: "%s"' % survey) # +------------------+ # | GET SURVEY ANIME | # +------------------+ print('Reading survey anime') fa = open(survey_anime_file_path, 'r', encoding='utf8') fa.readline() anime_series_map = {} special_anime_map = {} for line in fa: split = line.split('\t') series_str = split[0].strip() if series_str and not series_str.isspace(): anime_series = find_accompanying_anime(series_str.split(' | '), True) anime_series_map[series_str] = anime_series special_str = split[1].strip() if special_str and not special_str.isspace(): special_anime = find_accompanying_anime(special_str.split(' | '), False) special_anime_map[special_str] = special_anime # +---------------+ # | GET LATE ADDS | # +---------------+ if survey_late_adds_file_path: print('Reading late adds') fl = open(survey_late_adds_file_path, 'r', encoding='utf8') fl.readline() for line in fl: split = line.split('\t') anime_str_maybe = split[0].strip() add_response_count_str_maybe = split[1].strip() search_int = re.search(r'\d+', add_response_count_str_maybe) if search_int: add_response_count = int(search_int.group()) if anime_str_maybe in anime_series_map.keys(): anime = anime_series_map[anime_str_maybe] elif anime_str_maybe in special_anime_map.keys(): anime = special_anime_map[anime_str_maybe] else: continue if not anime: continue sar = SurveyAdditionRemoval( anime=anime, is_addition=True, response_count=add_response_count, survey=survey, ) sar.save() print('Found late add: "%s" added at %i responses' % (str(anime), add_response_count)) # +---------------------+ # | READ SURVEY RESULTS | # +---------------------+ print('Reading survey results') f = open(survey_file_path, 'r', encoding='utf8') headers = f.readline().split('\t') animeresponse_list = [] line_ctr = 2 for line in f: split = line.split('\t') # +-----------------+ # | CREATE RESPONSE | # +-----------------+ timestamp_str = split[0] date_split = timestamp_str.split(' ')[0].split('/') time_split = timestamp_str.split(' ')[1].split(':') timestamp = datetime( year=int(date_split[2]), month=int(date_split[0]), day=int(date_split[1]), hour=int(time_split[0]), minute=int(time_split[1]), second=int(time_split[2]), ) age_str = split[1] age = float(age_str) if age_str != '' else None gender_str = split[2] if gender_str == 'Male': gender = Response.Gender.MALE elif gender_str == 'Female': gender = Response.Gender.FEMALE elif gender_str == 'Other': gender = Response.Gender.OTHER else: gender = None response = Response( timestamp=timestamp, survey=survey, age=age, gender=gender ) response.save() # +-------------------------+ # | GENERATE ANIMERESPONSES | # +-------------------------+ animeresponse_map = { anime: AnimeResponse(anime=anime, response=response, watching=False, underwatched=False) for anime in list(anime_series_map.values()) + list(special_anime_map.values()) if anime is not None } # Get watching anime watching_anime_str = split[3] watching_anime_list = parse_anime_strlist(watching_anime_str, anime_series_map) for anime in watching_anime_list: animeresponse_map[anime].watching = True # Get underwatched anime if post-season if not survey.is_preseason: underwatched_anime_str = split[4] underwatched_anime_list = parse_anime_strlist(underwatched_anime_str, anime_series_map) for anime in underwatched_anime_list: animeresponse_map[anime].underwatched = True header_idx = 4 if survey.is_preseason else 5 # Get anime scores while headers[header_idx].startswith('How good '): header = headers[header_idx].strip() start = header.index('[') end = header.rindex(']') anime_str = header[start+1:end].strip() anime = anime_series_map[anime_str] anime_score_str = split[header_idx].strip() if anime and anime_score_str and not anime_score_str.isspace() and anime_score_str != 'N/A': anime_score = int(anime_score_str[0]) animeresponse_map[anime].score = anime_score header_idx += 1 # Get surprises/disappointments while headers[header_idx].startswith('What are your '): header = headers[header_idx].strip() start = header.index('[') end = header.rindex(']') anime_str = header[start+1:end].strip() anime = anime_series_map[anime_str] expectations_str = split[header_idx].strip() if anime and expectations_str and not expectations_str.isspace() and expectations_str != 'N/A': expectations = AnimeResponse.Expectations.SURPRISE if expectations_str == 'Surprise' else AnimeResponse.Expectations.DISAPPOINTMENT animeresponse_map[anime].expectations = expectations header_idx += 1 # Get watching special anime watching_special_anime_str = split[header_idx] watching_special_anime_list = parse_anime_strlist(watching_special_anime_str, special_anime_map) for anime in watching_special_anime_list: animeresponse_map[anime].watching = True header_idx += 1 # Get special anime scores while header_idx < len(headers) and headers[header_idx].startswith('How good '): header = headers[header_idx].strip() start = header.index('[') end = header.rindex(']') anime_str = header[start+1:end].strip() anime = special_anime_map[anime_str] anime_score_str = split[header_idx].strip() if anime and anime_score_str and not anime_score_str.isspace() and anime_score_str != 'N/A': anime_score = int(anime_score_str[0]) animeresponse_map[anime].score = anime_score header_idx += 1 # Filter and save AnimeResponses for animeresponse in animeresponse_map.values(): if survey.is_preseason: keep_animeresponse = animeresponse.watching == True or animeresponse.score is not None else: keep_animeresponse = animeresponse.watching == True if keep_animeresponse: animeresponse_list.append(animeresponse) # Bulk create for performance (SQLite only allows max 999 variables per query, >800 to be safe) if len(animeresponse_list) > 800: AnimeResponse.objects.bulk_create(animeresponse_list) animeresponse_list.clear() print('Parsed response %i: "%s: %s %s, %s watching, %s special watching"' % (line_ctr, str(timestamp), str(age) if age is not None else '----', str(gender) if gender is not None else '-', str(len(watching_anime_list)), str(len(watching_special_anime_list)))) line_ctr += 1 #print('Watching anime: %s' % str('\n'.join([str(anime) for anime in watching_anime_list]))) # answer = input('Continue? (Y/N) ') # if answer.lower() == 'n': # break AnimeResponse.objects.bulk_create(animeresponse_list) animeresponse_list.clear()