def create_survey(request): template = loader.get_template('surveys/create_survey_page.html') survey_info_form = SurveyInfoForm survey_requirements_form = SurveyRequirementsForm if request.method == 'POST': survey_info_form = SurveyInfoForm(request.POST) survey_requirements_form = SurveyRequirementsForm(request.POST) if survey_info_form.is_valid() and survey_requirements_form.is_valid(): survey = Survey() survey.info = survey_info_form.save() survey.requirements = survey_requirements_form.save() survey.save() return HttpResponseRedirect(reverse('list_surveys')) context = RequestContext(request, { 'group': request.user.groups.all()[0].name, 'user_id': request.user.id, 'survey_info_form': survey_info_form, 'survey_requirements_form': survey_requirements_form, 'page_label': 'Create a new survey', 'cancel_button_text': 'Cancel', 'show_create_button': True, 'create_button_text': 'Create' }) return HttpResponse(template.render(context))
def test_raise_no_more_available_places_error_when_places_is_zero(self): """ Creating a survey response must raise no more available error when places is zero. """ with self.assertRaises(NoMoreAvailablePlacesError): survey = Survey(name="no more", available_places=0, user_id=1) survey.save() response = SurveyResponse(survey=survey, user_id=2) response.save()
def test_reduce_available_places_after_creating_survey_response(self): """ Creating a survey response must reduce by one the number of availabel places. """ survey = Survey(name="first", available_places=10, user_id=1) survey.save() response = SurveyResponse(survey=survey, user_id=2) response.save() survey = Survey.objects.get(pk=survey.pk) self.assertIs(survey.available_places, 9)
def new_survey(request): body = json.loads(request.body) survey_obj = Survey( author_id=body["author_id"], area_id=body["area_id"], name=body["name"], type=body["type"], ) survey_obj.save() return JsonResponse({"data": body})
def create_survey(name: str, author_id: int, area_id: int, type_survey: str = "Formal", id: int = 1): # noqa: E501 survey = Survey(id=id, name=name, author_id=author_id, area_id=area_id, type=type_survey) # noqa: E501 survey.save() return survey
def save_survey(self, survey_id, created_at, updated_at, survey_unique_value, status, order_id, internal_comment, user_comment): created_at_aware, updated_at_aware = self.make_datetime_aware_of_utc( created_at, updated_at) try: order = Order.objects.get(id=order_id) self.surveys.append( Survey( id=survey_id, created_at=created_at_aware, updated_at=updated_at_aware, survey_unique_value=survey_unique_value, status=status, order_id=order.id, internal_comment=internal_comment, user_comment=user_comment, )) self.counter += 1 except Order.DoesNotExist: self.not_found_orders['orders'].append(order_id)
def validate(self, attrs): # In partial update you don't need to pass all data, you can omit something. # And if `start_at` or `end_at` will be omitted, `.clean()` will set those fields to None, # and since you cannot compare None and None, so this code # # >>> if self.end_at > self.start_at: ... # # will raise an error. if getattr(self.context.get('view'), 'action', None) == 'partial_update': attrs.setdefault('start_at', timezone.now()) attrs.setdefault('end_at', timezone.now() + timedelta(days=1)) # Since serializers do not call `.full_clean()` method on models instances, # but in this case it is needed, workaround is used here. # https://www.django-rest-framework.org/community/3.0-announcement/#differences-between-modelserializer-validation-and-modelform fake = Survey(**attrs) fake.clean() return attrs
def create_survey(request): template = loader.get_template('surveys/create_survey_page.html') survey_info_form = SurveyInfoForm survey_requirements_form = SurveyRequirementsForm if request.method == 'POST': survey_info_form = SurveyInfoForm(request.POST) survey_requirements_form = SurveyRequirementsForm(request.POST) if survey_info_form.is_valid() and survey_requirements_form.is_valid(): survey = Survey() survey.info = survey_info_form.save() survey.requirements = survey_requirements_form.save() survey.save() return HttpResponseRedirect(reverse('list_surveys')) context = RequestContext( request, { 'group': request.user.groups.all()[0].name, 'user_id': request.user.id, 'survey_info_form': survey_info_form, 'survey_requirements_form': survey_requirements_form, 'page_label': 'Create a new survey', 'cancel_button_text': 'Cancel', 'show_create_button': True, 'create_button_text': 'Create' }) return HttpResponse(template.render(context))
def test_list_all_surveys(self): """ Ensure we can list created surveys. """ Survey(name='test_list_all_surveys', available_places=1, user_id=1).save() url = 'http://testserver/surveys/' response = self.client.get(url, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data, [{ 'id': 1, 'name': 'test_list_all_surveys', 'available_places': 1, 'user_id': 1 }])
def test_create_survey_response(self): """ Ensure we can create a new survey response object. """ Survey(name='test3', available_places=1, user_id=1).save() url = 'http://testserver/surveys/1/responses/' data = {'user_id': 2} response = self.client.post(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertEqual(SurveyResponse.objects.count(), 1) survey_response = SurveyResponse.objects.get() self.assertEqual(survey_response.id, 1) self.assertEqual(survey_response.survey_id, 1) self.assertEqual(survey_response.user_id, 2) self.assertIsNotNone(survey_response.created_at)
def test_responses_to_survey(self): """ Ensure we can list created responses for a survey. """ now = timezone.now() Survey(name='test responses_to_survey', available_places=1, user_id=1).save() survey = Survey.objects.get() self.assertEqual(survey.id, 1) SurveyResponse(survey=survey, user_id=2, created_at=now).save() url = 'http://testserver/surveys/1/responses/' response = self.client.get(url, format='json') self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response.data[0]['id'], 1) self.assertEqual(response.data[0]['survey_id'], 1) self.assertEqual(response.data[0]['user_id'], 2) self.assertIsNotNone(response.data[0]['created_at'])
def open_survey_form(request, survey_uid, phase_id=None): """ View to open a survey form. If survey is simple, default phase is opened else phase_id is used. **Type**: GET **Authors**: Gagandeep Singh """ try: survey = Survey.objects.get(survey_uid=survey_uid) # Check status if survey.status == Survey.ST_READY: # Check date now = timezone.now().date() if survey.start_date <= now <= survey.end_date: #TODO: Audience filter # Obtain phase if survey.type == Survey.TYPE_SIMPLE: phase = survey.phases[0] else: try: phase = survey.phases.filter(id=phase_id) except SurveyPhase.DoesNotExist: raise Survey.DoesNotExist("Invalid survey phase.") # --- All check passed --- form = phase.form template = 'themes/{}/form_base.html'.format(form.theme_skin.theme.code) data = { 'context': 'SURVEY', 'survey': survey, 'phase': phase, 'form': form, 'title': survey.title, 'theme': form.theme_skin.theme, 'skin': form.theme_skin, 'lookup_translations': form.get_translation_lookup(), 'DEFAULT_LANGUAGE_CODE': Language.DEFAULT_LANGUAGE_CODE, # Fallback language incase translation not found #TODO: Set user properties 'reg_user': RegisteredUser.objects.get(user__username=request.GET['username']), 'USER_DEFAULT_LANG_CODE': 'hin' } return render(request, template, data) # --- /All check passed --- else: raise Http404("Sorry! This survey has been completed.") elif survey.status == Survey.ST_STOPPED: raise Http404("Sorry! This survey has been concluded.") else: raise Http404("This survey is not currently active. Please try some other time.") except Survey.DoesNotExist: # Invalid link raise Http404("Invalid survey.")
def createSurvey(request): if request.is_ajax(): # <editor-fold desc="CHECKS"> checked = False title = request.POST.get('title') description = request.POST.get('description') linkAccess = request.POST.get('linkAccess') if linkAccess == 'true': linkAccess = True else: linkAccess = False linkAccess_text = request.POST.get('linkAccess-text-survey') if not check_string(title): messages.error(request, "Incorrect title") if not check_string(description): messages.error(request, "Incorrect description") if not linkAccess_text.isalnum(): messages.error( request, "Link may only contain digits and letters and should not be empty" ) questionFilled = True filled = True different = True questionDifferent = True stop = 0 enoughAnswers = True i = 0 while request.POST.get(f'question{i + 1}', default=None) != None: if not check_string(request.POST.get(f'question{i + 1}')): questionFilled = False for j in range(i): if request.POST.get(f'question{i + 1}') == request.POST.get( f'question{j + 1}'): questionDifferent = False break for j in range(10): if request.POST.get(f'answer{i + 1}_{j + 1}', default=None) != None: if not check_string( request.POST.get(f'answer{i + 1}_{j + 1}')): filled = False for k in range(j): if request.POST.get( f'answer{i + 1}_{j + 1}') == request.POST.get( f'answer{i + 1}_{k + 1}'): different = False break else: stop = j break if stop <= 1: enoughAnswers = False i += 1 if i == 0: messages.error(request, "Number of questions should be at least 1") if not questionDifferent: messages.error(request, "Questions should be different") if not questionFilled: messages.error(request, "Questions should not be empty") if not enoughAnswers: messages.error( request, "Number of answers for each question should be at least 2") if not different: messages.error(request, "Answers for each question should be different") if not filled: messages.error(request, "Answers should not be empty") if len(messages.get_messages(request)) == 0: checked = True # </editor-fold> data = {} data['success'] = True if checked: linkCheck = True try: survey = Survey.objects.get(url=linkAccess_text) except ObjectDoesNotExist: pass else: linkCheck = False messages.error(request, "Survey with such link already exists") if linkCheck: survey = Survey( title=title, description=description, url=linkAccess_text, isLocked=linkAccess, creator=User.objects.get(username=request.user.username)) survey.save() i = 0 while request.POST.get(f'question{i + 1}', default=None) != None: surveyQuestion = SurveyQuestion( survey=survey, text=request.POST.get(f'question{i + 1}'), multipleChoice=( request.POST.get(f'multichoice{i + 1}') == 'true')) surveyQuestion.save() for j in range(10): if request.POST.get(f'answer{i + 1}_{j + 1}', default=None) != None: surveyAnswer = SurveyAnswer( surveyQuestion=surveyQuestion, text=request.POST.get( f'answer{i + 1}_{j + 1}')) surveyAnswer.save() else: break i += 1 if len(messages.get_messages(request)) == 0: messages.success(request, 'Check succeeded') # <editor-fold desc="SEND-MESSAGES"> sended_messages = [] for message in messages.get_messages(request): sended_messages.append({ "level": message.level, "message": message.message, "extra_tags": message.tags, }) data['messages'] = sended_messages # </editor-fold> return HttpResponse(json.dumps(data), content_type="application/json") context = { 'answers_len': 5, } return render(request, 'surveyCreation.html', context)
survey_json = json.load(f) for survey in survey_json: try: survey = Survey(person=Person.objects.get(pk=int(survey['person'])), job=Job.objects.get(pk=int(survey['job'])), creation_date=survey['creation_date'], name=survey['name'], md=survey['md'], inc=survey['inc'], azi=survey['azi'], tvd=survey['tvd'], north=survey['north'], east=survey['east'], vertical_section=survey['vertical_section'], dogleg=survey['dogleg'], build_rate=survey['build_rate'], turn_rate=survey['turn_rate'], calculated_tf=survey['calculated_tf'], calculated_ang=survey['calculated_ang'], clos_dist=survey['clos_dist'], clos_azi=survey['clos_azi'], mag_total=survey['mag_total'], grav_total=survey['grav_total'], dip=survey['number'], temp=survey['temp'], zero_vs=survey['zero_vs'], step_out=survey['step_out']) survey.save() except: print("Survey Not Loaded")