예제 #1
0
파일: survey.py 프로젝트: ailan12345/app1
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')
예제 #2
0
 def get_caption_group_together(self):
     """ A descriptive text for the group_together option. """
     caption = ""
     if self.group_together:
         if self.cardinality is None:
             loop_dict = self.group_together
         else:
             # Looping only on the value really used in the answers
             loop_dict = self.cardinality
         has_and = False
         for key in loop_dict:
             values = self.group_together.get(key)
             if values is None:
                 # group_together does not contain every answers
                 continue
             standardized_values = Question.standardize_list(
                 values, self.group_by_letter_case, self.group_by_slugify
             )
             standardized_key = Question.standardize(key, self.group_by_letter_case, self.group_by_slugify)
             relevant_values = [v for v in standardized_values if v != standardized_key]
             if not relevant_values:
                 # If there is no relevant value the group_together was just
                 # a placeholder ex Yes for [yes Yës yEs]
                 continue
             # We duplicate the translations so makemessage find it
             caption += "with '{}' standing for ".format(key)
             for value in values:
                 caption += "'{}' {} ".format(value, _("or"))
             caption = caption[: -len("{} ".format(_("or")))]
             has_and = True
             caption += "{} ".format(_("and"))
         if has_and:
             # We remove the final "and " if there is one
             caption = caption[: -len("{} ".format(_("and")))]
     return caption
예제 #3
0
def manage_loop(request, question_id):
    question = Question.get(id=question_id)
    batch = QuestionSet.get(pk=question.qset.pk)
    cancel_url = '../'
    existing_loop = getattr(question, 'loop_started', None)
    looping_form = LoopingForm(question, instance=existing_loop)
    if request.method == "POST":
        looping_form = LoopingForm(
            question,
            instance=existing_loop,
            data=request.POST)
        if looping_form.is_valid():
            looping_form.save()
            messages.success(request, 'Loop Logic successfully added.')
            return HttpResponseRedirect(
                reverse(
                    'qset_questions_page',
                    args=(
                        batch.pk,
                    )))
    breadcrumbs = Question.edit_breadcrumbs(qset=batch)

    if breadcrumbs:
        request.breadcrumbs(breadcrumbs)
        cancel_url = breadcrumbs[-1][1]
    context = {
        'loop_form': looping_form,
        'button_label': 'Save',
        'question': question,
        'cancel_url': cancel_url}
    return render(request, "set_questions/loop.html", context)
예제 #4
0
def add_logic(request, qset_id, question_id):
    question = Question.get(id=question_id)
    batch = QuestionSet.get(id=qset_id)
    QuestionForm = get_question_form(batch.question_model())
    response = None
    cancel_url = '../'
    logic_form = LogicForm(question)
    question_rules_for_batch = {}
    #     question_rules_for_batch[question] = question.rules_for_batch(batch)
    if request.method == "POST":
        logic_form = LogicForm(question, data=request.POST)
        if logic_form.is_valid():
            logic_form.save()
            messages.success(request, 'Logic successfully added.')
            response = HttpResponseRedirect(
                reverse('qset_questions_page', args=(batch.pk, )))
    breadcrumbs = Question.edit_breadcrumbs(qset=batch)
    if breadcrumbs:
        request.breadcrumbs(breadcrumbs)
        cancel_url = breadcrumbs[-1][1]
    context = {
        'logic_form': logic_form,
        'button_label': 'Save',
        'question': question,
        'USSD_MAX_CHARS': settings.USSD_MAX_CHARS,
        'rules_for_batch': question_rules_for_batch,
        'questionform': QuestionForm(batch, parent_question=question),
        'modal_action': reverse('add_qset_subquestion_page',
                                args=(batch.pk, )),
        'class': 'question-form',
        'batch_id': qset_id,
        'batch': batch,
        'cancel_url': cancel_url
    }
    return response or render(request, "set_questions/logic.html", context)
예제 #5
0
def manage_loop(request, question_id):
    question = Question.get(id=question_id)
    batch = QuestionSet.get(pk=question.qset.pk)
    cancel_url = '../'
    existing_loop = getattr(question, 'loop_started', None)
    looping_form = LoopingForm(question, instance=existing_loop)
    if request.method == "POST":
        looping_form = LoopingForm(question,
                                   instance=existing_loop,
                                   data=request.POST)
        if looping_form.is_valid():
            looping_form.save()
            messages.success(request, 'Loop Logic successfully added.')
            return HttpResponseRedirect(
                reverse('qset_questions_page', args=(batch.pk, )))
    breadcrumbs = Question.edit_breadcrumbs(qset=batch)

    if breadcrumbs:
        request.breadcrumbs(breadcrumbs)
        cancel_url = breadcrumbs[-1][1]
    context = {
        'loop_form': looping_form,
        'button_label': 'Save',
        'question': question,
        'cancel_url': cancel_url
    }
    return render(request, "set_questions/loop.html", context)
예제 #6
0
    def test_votes(self):
        question = Question('Are you from India?')
        question.vote('yes')
        db.session.add(question)
        db.session.commit()

        self.assertEqual(question.number_of_yes_votes, 1)
        self.assertEqual(question.number_of_no_votes, 0)
        self.assertEqual(question.number_of_maybe_votes, 0)
예제 #7
0
 def post(self, request):
     data = json.loads(request.POST.get('r'))
     slug = slugify(data.get('slug', ''))
     try:
         survey = Survey.objects.create(slug=slug, title=data.get('title', ''), description=data.get('description', ''))
     except IntegrityError:
         return HttpResponse(json.dumps({'status': 'failure', 'error': _('That SLUG already exists')}), mimetype='application/json')
     questions = data.get('questions', [])
     Question.add_questions(questions, survey)
     return HttpResponse(json.dumps({'status': 'success', 'url': reverse('surveydashboard', args=[survey.slug])}), mimetype='application/json')
예제 #8
0
def addquestions():
	Q1 = Question(question_text = "What is your favorite color?")
	Q2 = Question(question_text = "What is your favorite food?")
	Q3 = Question(question_text = "What is your favorite genre of music?")
	Q1.save()
	Q2.save()
	Q3.save()
예제 #9
0
    def mutate(self,
               info,
               survey_id,
               payload: str,
               options: list = None,
               allow_multiple_answer=False,
               *args,
               **kwargs):
        new_question: QuestionORM = QuestionORM.create(
            survey_id=survey_id,
            allow_multiple_answer=allow_multiple_answer,
            payload=payload)

        option_list_field = []
        for option in options or []:
            new_option: OptionORM = OptionORM.create(
                question_id=new_question.id,
                payload=option.payload,
            )
            option_list_field.append(
                Option(id=new_option.id,
                       question_id=new_option.question_id,
                       payload=new_option.payload))

        question = Question(
            id=new_question.id,
            survey_id=new_question.survey_id,
            allow_multiple_answer=allow_multiple_answer,
            payload=payload,
        )

        return CreateQuestion(question=question, message='ok')
예제 #10
0
def _remove(request, question_id):
    question = Question.get(pk=question_id)
    batch_id = question.qset.id
    batch = QuestionSet.get(pk=batch_id)
    redirect_url = reverse('qset_questions_page', args=(batch_id, ))
    if question.total_answers() > 0:
        messages.error(
            request,
            "Cannot delete question that has been answered at least once.")
    else:
        _kill_zombies(batch.zombie_questions())
        if question:
            success_message = "Question successfully deleted."
            # % ("Sub question" if question.subquestion else "Question"))
            messages.success(request, success_message)
        next_question = batch.next_inline(question)
        previous_inline = question.connecting_flows.filter(
            validation__isnull=True)
        if previous_inline.exists() and next_question:
            QuestionFlow.objects.create(question=previous_inline[0].question,
                                        next_question=next_question)
        elif next_question:
            # need to delete the previous flow for the next question
            batch.start_question = next_question
            batch.save()
        question.connecting_flows.all().delete()
        question.flows.all().delete()
        question.delete()
    return HttpResponseRedirect(redirect_url)
예제 #11
0
def _remove(request, question_id):
    question = Question.get(pk=question_id)
    batch_id = question.qset.id
    batch = QuestionSet.get(pk=batch_id)
    redirect_url = reverse('qset_questions_page', args=(batch_id, ))
    if question.total_answers() > 0:
        messages.error(
            request,
            "Cannot delete question that has been answered at least once.")
    else:
        _kill_zombies(batch.zombie_questions())
        if question:
            success_message = "Question successfully deleted."
            # % ("Sub question" if question.subquestion else "Question"))
            messages.success(request, success_message)
        next_question = batch.next_inline(question)
        previous_inline = question.connecting_flows.filter(validation__isnull=True)
        if previous_inline.exists() and next_question:
            QuestionFlow.objects.create(
                question=previous_inline[0].question,
                next_question=next_question)
        elif next_question:
            # need to delete the previous flow for the next question
            batch.start_question = next_question
            batch.save()
        question.connecting_flows.all().delete()
        question.flows.all().delete()
        question.delete()
    return HttpResponseRedirect(redirect_url)
예제 #12
0
def index(request, qset_id):
    # now I'm gonna call question set a batch of questions.\
        #If there's time, I'll rename them properly
    # So don't get confused :)
    try:
        batch = QuestionSet.get(pk=qset_id)
    except QuestionSet.DoesNotExist:
        raise Http404("No QuestionSet Model matches the given query.")
    questions = batch.questions_inline()
    request_data = request.GET if request.method == 'GET' else request.POST
    question_filter_form = QuestionFilterForm(data=request_data, qset=batch)
    search_fields = ['identifier', 'text', ]
    qset_questions = batch.questions.all()
    if 'q' in request_data:
        questions = get_filterset(qset_questions, request_data['q'], search_fields)
    if 'question_types' in request_data:
        relevant_ids = list(question_filter_form.filter(
            qset_questions).values_list('id', flat=True))
        questions = [q for q in questions if q.id in relevant_ids]
    # now maintain same inline other exclusing questions in
    breadcrumbs = Question.index_breadcrumbs(qset=batch)
    if breadcrumbs:
        request.breadcrumbs(breadcrumbs)
    context = {'questions': questions, 'request': request, 'batch': batch,
               'question_filter_form': question_filter_form,
               'placeholder': 'identifier, text',
               'template_file': 'interviews/answer.html',
               'is_preview': True
               # caution atleast on ODK access
               #  at least on access must exist
               }
    return render(request, 'set_questions/index.html', context)
예제 #13
0
def edit(request, question_id):
    question = Question.get(id=question_id)
    batch = QuestionSet.get(pk=question.qset.pk)
    response, context = _render_question_view(
        request, batch, instance=question)
    context['page_title '] = 'Edit Question'
    return response or render(request, 'set_questions/new.html', context)
예제 #14
0
def insert(request, prev_quest_id):
    prev_question = Question.get(pk=prev_quest_id)
    batch = QuestionSet.get(pk=prev_question.qset.pk)
    response, context = _render_question_view(
        request, batch, prev_question=prev_question)
    context['prev_question'] = prev_question
    return response or render(request, 'set_questions/new.html', context)
예제 #15
0
 def defaultTest(self):
     q = Question("abcacb")
     db.session.add(q)
     db.session.commit()
     self.assertEqual(q.nu_maybe, 0)
     self.assertEqual(q.nu_no, 0)
     self.assertEqual(q.nu_yes, 0)
예제 #16
0
 def save(self, *args, **kwargs):
     next_question = None
     desc = self._make_desc()
     if self.cleaned_data['action'] in [
             self.ASK_SUBQUESTION, self.SKIP_TO, self.BACK_TO]:
         next_question = Question.get(pk=self.cleaned_data['next_question'])
     if self.cleaned_data['action'] == self.REANSWER:
         next_question = self.question
     validation = ResponseValidation.objects.create(validation_test=self.cleaned_data['condition'])
     flow = QuestionFlow.objects.create(question=self.question,
                                        validation=validation,
                                        next_question=next_question,
                                        desc=desc)
     if self.cleaned_data['action'] == self.ASK_SUBQUESTION:
         # connect back to next inline question of the main
         QuestionFlow.objects.create(
             question=next_question,
             desc=desc,
             next_question=self.batch.next_inline(
                 self.question))
     if self.cleaned_data['condition'] == 'between':
         TextArgument.objects.create(validation=validation, position=0, param=self.cleaned_data['min_value'])
         TextArgument.objects.create(validation=validation, position=1, param=self.cleaned_data['max_value'])
     else:
         value = self.cleaned_data.get('value', '')
         if self.question.answer_type in [
                 MultiChoiceAnswer.choice_name(),
                 MultiSelectAnswer.choice_name()]:
             value = self.cleaned_data['option']
         TextArgument.objects.create(validation=validation, position=0, param=value)
     # clean up now, remove all zombie questions
     self.question.qset.zombie_questions().delete()
예제 #17
0
def insert(request, prev_quest_id):
    prev_question = Question.get(pk=prev_quest_id)
    batch = QuestionSet.get(pk=prev_question.qset.pk)
    response, context = _render_question_view(request,
                                              batch,
                                              prev_question=prev_question)
    context['prev_question'] = prev_question
    return response or render(request, 'set_questions/new.html', context)
예제 #18
0
def edit(request, question_id):
    question = Question.get(id=question_id)
    batch = QuestionSet.get(pk=question.qset.pk)
    response, context = _render_question_view(request,
                                              batch,
                                              instance=question)
    context['page_title '] = 'Edit Question'
    return response or render(request, 'set_questions/new.html', context)
예제 #19
0
def _render_question_view(request, batch, instance=None, prev_question=None):
    if instance is None and prev_question is None:
        prev_question = batch.last_question_inline()
    elif prev_question is None:
        try:
            prev_inlines = instance.previous_inlines()
            if prev_inlines:
                prev_question = prev_inlines[-1]
        except ValidationError:
            pass
    button_label = 'Create'
    options = None
    response = None
    QuestionForm = get_question_form(batch.question_model())
    if instance:
        button_label = 'Save'
        options = instance.options.all().order_by('order')
        # options = [option.text.strip()\
        #for option in options] if options else None
    if request.method == 'POST':
        question_form = QuestionForm(batch,
                                     data=request.POST,
                                     instance=instance,
                                     prev_question=prev_question)
        response, question_form = _process_question_form(
            request, batch, response, question_form)
    else:
        question_form = QuestionForm(batch,
                                     instance=instance,
                                     prev_question=prev_question)
    context = {
        'button_label': button_label,
        'id': 'add-question-form',
        'instance': instance,
        'request': request,
        'class': 'question-form',
        'USSD_MAX_CHARS': settings.USSD_MAX_CHARS,
        'batch': batch,
        'prev_question': prev_question,
        # 'prev_question': prev_question,
        'cancel_url': reverse('qset_questions_page', args=(batch.pk, )),
        'questionform': question_form,
        'response_validation_form': ResponseValidationForm(),
        'model_name': batch.__class__.__name__
    }

    if options:
        #options = filter(lambda text: text.strip(),
        #list(OrderedDict.fromkeys(options)))
        # options = map(lambda option: re.sub("[%s]" % \
        #settings.USSD_IGNORED_CHARACTERS, '', option), options)
        # map(lambda option: re.sub("  ", ' ', option), options)
        context['options'] = options
    breadcrumbs = Question.edit_breadcrumbs(qset=batch)
    if breadcrumbs:
        request.breadcrumbs(breadcrumbs)
    return response, context
예제 #20
0
 def post(self, request, slug):
     survey = self.get_object()
     data = json.loads(request.POST.get('r'))
     questions = data.get('questions', [])
     # delete existing questions
     # due to cascading deletes, this will also delete choices
     survey.question_set.all().delete()
     # edit the title if it has changed
     survey.title = data.get('title', '')
     survey.description = data.get('description', '')
     # edit slug if it has changed
     survey.slug = slugify(data.get('slug', ''))
     try:
         survey.save()
     except IntegrityError:
         return HttpResponse(json.dumps({'status': 'failure', 'error': _('That SLUG already exists')}), mimetype='application/json')
     Question.add_questions(questions, survey)
     return HttpResponse(json.dumps({'status': 'success', 'url': reverse('surveydashboard', args=[survey.slug])}), mimetype='application/json')
예제 #21
0
def _save_subquestion(request, batch_id, instance=None):
    # possible subquestions are questions not bound to any interviewer yet
    batch = QuestionSet.get(pk=batch_id)
    QuestionForm = get_question_form(batch.question_model())
    questionform = QuestionForm(batch, instance=instance)
    if request.method == 'POST':
        questionform = QuestionForm(
            batch, data=request.POST, instance=instance)
        if questionform.is_valid():
            if instance:
                zombify = False
            else:
                zombify = True
            question = questionform.save(zombie=zombify)
            if request.is_ajax():
                return HttpResponse(
                    json.dumps(
                        {
                            'id': question.pk,
                            'text': question.text,
                            'identifier': question.identifier}),
                    content_type='application/json')
            messages.info(request, 'Sub Question saved')
    if instance:
        heading = 'Edit Subquestion'
    else:
        heading = 'New Subquestion'
    context = {
        'questionform': questionform,
        'button_label': 'Create',
        'id': 'add-sub_question-form',
        'USSD_MAX_CHARS': settings.USSD_MAX_CHARS,
        'save_url': reverse(
            '%s_home' %
            batch.resolve_tag()),
        'cancel_url': reverse(
            'qset_questions_page',
            args=(
                batch.pk,
            )),
        'class': 'question-form',
        'heading': heading}
    breadcrumbs = Question.edit_breadcrumbs(qset=batch)
    if breadcrumbs:
        request.breadcrumbs(breadcrumbs)
    template_name = 'set_questions/new.html'
    if request.is_ajax():
        template_name = 'set_questions/_add_question.html'
        return render(request, template_name, context)
    else:
        return HttpResponseRedirect(
            reverse(
                'qset_questions_page',
                args=(
                    batch.pk,
                )))
예제 #22
0
파일: views.py 프로젝트: hoanguyen401/flask
def add():
    if request.form['text'].strip() != '':
        newQ = Question(question_text = request.form['text'])
        db.session.add(newQ)
        db.session.commit()
        message = "Question is created"
    else:
        message = "Pool question is full"    
    context = {"questions": Question.query.all(), "Message": message}
    return render_template('index.html', **context)
예제 #23
0
def question_validators(request):
    values = {}
    if request.GET.get('id'):
        for question in QuestionSet.get(
                id=request.GET.get('id')).all_questions:
            values['%s' % question.id] = [
                validator for validator in question.validator_names()]
    elif request.GET.get('ques_id'):
        values = Question.get(id=request.GET.get('ques_id')).validator_names()
    return HttpResponse(json.dumps(values), content_type='application/json')
예제 #24
0
def _render_question_view(request, batch, instance=None, prev_question=None):
    if instance is None and prev_question is None:
        prev_question = batch.last_question_inline()
    elif prev_question is None:
        try:
            prev_inlines = instance.previous_inlines()
            if prev_inlines:
                prev_question = prev_inlines[-1]
        except ValidationError:
            pass
    button_label = 'Create'
    options = None
    response = None
    QuestionForm = get_question_form(batch.question_model())
    if instance:
        button_label = 'Save'
        options = instance.options.all().order_by('order')
        # options = [option.text.strip()\
            #for option in options] if options else None
    if request.method == 'POST':
        question_form = QuestionForm(
            batch,
            data=request.POST,
            instance=instance,
            prev_question=prev_question)
        response, question_form = _process_question_form(request, batch, response, question_form)
    else:
        question_form = QuestionForm(
            batch, instance=instance, prev_question=prev_question)
    context = {'button_label': button_label,
               'id': 'add-question-form',
               'instance':instance,
               'request': request,
               'class': 'question-form',
                'USSD_MAX_CHARS': settings.USSD_MAX_CHARS,
               'batch': batch,
               'prev_question': prev_question,
               # 'prev_question': prev_question,
               'cancel_url': reverse('qset_questions_page', args=(batch.pk, )),
               'questionform': question_form,
               'response_validation_form': ResponseValidationForm(),
               'model_name' : batch.__class__.__name__
               }

    if options:
        #options = filter(lambda text: text.strip(),
            #list(OrderedDict.fromkeys(options)))
        # options = map(lambda option: re.sub("[%s]" % \
            #settings.USSD_IGNORED_CHARACTERS, '', option), options)
        # map(lambda option: re.sub("  ", ' ', option), options)
        context['options'] = options
    breadcrumbs = Question.edit_breadcrumbs(qset=batch)
    if breadcrumbs:
        request.breadcrumbs(breadcrumbs)
    return response, context
예제 #25
0
def create_questions():
    if request.form["question_text"].strip() != "":
        new_question = Question(question_text=request.form["question_text"])
        db.session.add(new_question) 
        db.session.commit()
        message = "Succesfully added a new poll!"
    else:
        message = "Poll question should not be an empty string!"

    context = {'questions': Question.query.all(), 'message': message}
    return render_template('index.html', **context) 
예제 #26
0
def question_validators(request):
    values = {}
    if request.GET.get('id'):
        for question in QuestionSet.get(
                id=request.GET.get('id')).all_questions:
            values['%s' % question.id] = [
                validator for validator in question.validator_names()
            ]
    elif request.GET.get('ques_id'):
        values = Question.get(id=request.GET.get('ques_id')).validator_names()
    return HttpResponse(json.dumps(values), content_type='application/json')
예제 #27
0
    def mutate(self, info, id, payload, allow_multiple_answer, options, *args,
               **kwargs):
        question = QuestionORM.get_by_id(id)
        if not question:
            raise GraphQLError('question.doesNotExist')

        question.update(payload=payload,
                        allow_multiple_answer=allow_multiple_answer)
        EditQuestion._update_options(options)

        return EditQuestion(message='ok')
예제 #28
0
def question_options(request):
    values = {}
    if request.GET.get('id'):
        for question in QuestionSet.get(
                id=request.GET.get('id')).all_questions:
            values['%s' % question.id] = dict([
                (opt.order, opt.text) for opt in question.options.all()
            ])
    elif request.GET.get('ques_id'):
        values = dict(
            Question.get(id=request.GET.get('ques_id')).options.values_list(
                'order', 'text'))
    return HttpResponse(json.dumps(values), content_type='application/json')
예제 #29
0
def add_logic(request, qset_id, question_id):
    question = Question.get(id=question_id)
    batch = QuestionSet.get(id=qset_id)
    QuestionForm = get_question_form(batch.question_model())
    response = None
    cancel_url = '../'
    logic_form = LogicForm(question)
    question_rules_for_batch = {}
#     question_rules_for_batch[question] = question.rules_for_batch(batch)
    if request.method == "POST":
        logic_form = LogicForm(question, data=request.POST)
        if logic_form.is_valid():
            logic_form.save()
            messages.success(request, 'Logic successfully added.')
            response = HttpResponseRedirect(
                reverse('qset_questions_page', args=(batch.pk, )))
    breadcrumbs = Question.edit_breadcrumbs(qset=batch)
    if breadcrumbs:
        request.breadcrumbs(breadcrumbs)
        cancel_url = breadcrumbs[-1][1]
    context = {
        'logic_form': logic_form,
        'button_label': 'Save',
        'question': question,
        'USSD_MAX_CHARS': settings.USSD_MAX_CHARS,
        'rules_for_batch': question_rules_for_batch,
        'questionform': QuestionForm(
            batch,
            parent_question=question),
        'modal_action': reverse(
            'add_qset_subquestion_page',
            args=(
                batch.pk,
            )),
        'class': 'question-form',
        'batch_id': qset_id,
        'batch': batch,
        'cancel_url': cancel_url}
    return response or render(request, "set_questions/logic.html", context)
예제 #30
0
def question_options(request):
    values = {}
    if request.GET.get('id'):
        for question in QuestionSet.get(
                id=request.GET.get('id')).all_questions:
            values['%s' % question.id] = dict(
                [(opt.order, opt.text) for opt in question.options.all()])
    elif request.GET.get('ques_id'):
        values = dict(
            Question.get(
                id=request.GET.get('ques_id')).options.values_list(
                'order',
                'text'))
    return HttpResponse(json.dumps(values), content_type='application/json')
예제 #31
0
def _save_subquestion(request, batch_id, instance=None):
    # possible subquestions are questions not bound to any interviewer yet
    batch = QuestionSet.get(pk=batch_id)
    QuestionForm = get_question_form(batch.question_model())
    questionform = QuestionForm(batch, instance=instance)
    if request.method == 'POST':
        questionform = QuestionForm(batch,
                                    data=request.POST,
                                    instance=instance)
        if questionform.is_valid():
            if instance:
                zombify = False
            else:
                zombify = True
            question = questionform.save(zombie=zombify)
            if request.is_ajax():
                return HttpResponse(json.dumps({
                    'id':
                    question.pk,
                    'text':
                    question.text,
                    'identifier':
                    question.identifier
                }),
                                    content_type='application/json')
            messages.info(request, 'Sub Question saved')
    if instance:
        heading = 'Edit Subquestion'
    else:
        heading = 'New Subquestion'
    context = {
        'questionform': questionform,
        'button_label': 'Create',
        'id': 'add-sub_question-form',
        'USSD_MAX_CHARS': settings.USSD_MAX_CHARS,
        'save_url': reverse('%s_home' % batch.resolve_tag()),
        'cancel_url': reverse('qset_questions_page', args=(batch.pk, )),
        'class': 'question-form',
        'heading': heading
    }
    breadcrumbs = Question.edit_breadcrumbs(qset=batch)
    if breadcrumbs:
        request.breadcrumbs(breadcrumbs)
    template_name = 'set_questions/new.html'
    if request.is_ajax():
        template_name = 'set_questions/_add_question.html'
        return render(request, template_name, context)
    else:
        return HttpResponseRedirect(
            reverse('qset_questions_page', args=(batch.pk, )))
예제 #32
0
 def clean_next_question(self):
     if self.cleaned_data['action'] in [
             self.ASK_SUBQUESTION, self.SKIP_TO, self.BACK_TO]:
         try:
             int(self.cleaned_data.get('next_question', ''))
             next_question = Question.get(
                 pk=self.cleaned_data['next_question'])
             if (hasattr(self.question, 'group') and hasattr(next_question, 'group')) \
                     and (self.question.group != next_question.group):
                 ValidationError(
                     'Assigning logic between questions of different groups is not allowed')
         except BaseException:
             raise ValidationError(
                 'Next question is required for Skip or Sub questions')
     return self.cleaned_data.get('next_question', '')
예제 #33
0
 def _validate_response(self, question, answer, interview=None):
     if interview is None:
         interview = self.interview
     answer_count = Answer.objects.count()
     questions = self.qset.flow_questions
     interview.respond(reply=answer, answers_context={})
     interview.refresh_from_db()
     self.assertEquals(Answer.objects.count(), answer_count+1)
     next_question = question.next_question(answer)
     # just confirm text value of this answer was saved
     self.assertTrue(interview.get_answer(question), str(answer))
     question = Question.get(id=question.id)
     # next test is valid
     if questions.index(question) < len(questions) - 1:
         self.assertEquals(next_question.id, questions[questions.index(question)+1].id)
         self.assertEquals(next_question.id, interview.last_question.id)
예제 #34
0
 def clean_next_question(self):
     if self.cleaned_data['action'] in [
             self.ASK_SUBQUESTION, self.SKIP_TO, self.BACK_TO
     ]:
         try:
             int(self.cleaned_data.get('next_question', ''))
             next_question = Question.get(
                 pk=self.cleaned_data['next_question'])
             if (hasattr(self.question, 'group') and hasattr(next_question, 'group')) \
                     and (self.question.group != next_question.group):
                 ValidationError(
                     'Assigning logic between questions of different groups is not allowed'
                 )
         except BaseException:
             raise ValidationError(
                 'Next question is required for Skip or Sub questions')
     return self.cleaned_data.get('next_question', '')
예제 #35
0
 def _validate_response(self, question, answer, interview=None):
     if interview is None:
         interview = self.interview
     answer_count = Answer.objects.count()
     questions = self.qset.flow_questions
     interview.respond(reply=answer, answers_context={})
     interview.refresh_from_db()
     self.assertEquals(Answer.objects.count(), answer_count + 1)
     next_question = question.next_question(answer)
     # just confirm text value of this answer was saved
     self.assertTrue(interview.get_answer(question), str(answer))
     question = Question.get(id=question.id)
     # next test is valid
     if questions.index(question) < len(questions) - 1:
         self.assertEquals(next_question.id,
                           questions[questions.index(question) + 1].id)
         self.assertEquals(next_question.id, interview.last_question.id)
예제 #36
0
    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"
예제 #37
0
 def save(self, *args, **kwargs):
     next_question = None
     desc = self._make_desc()
     if self.cleaned_data['action'] in [
             self.ASK_SUBQUESTION, self.SKIP_TO, self.BACK_TO
     ]:
         next_question = Question.get(pk=self.cleaned_data['next_question'])
     if self.cleaned_data['action'] == self.REANSWER:
         next_question = self.question
     validation = ResponseValidation.objects.create(
         validation_test=self.cleaned_data['condition'])
     flow = QuestionFlow.objects.create(question=self.question,
                                        validation=validation,
                                        next_question=next_question,
                                        desc=desc)
     if self.cleaned_data['action'] == self.ASK_SUBQUESTION:
         # connect back to next inline question of the main
         QuestionFlow.objects.create(question=next_question,
                                     desc=desc,
                                     next_question=self.batch.next_inline(
                                         self.question))
     if self.cleaned_data['condition'] == 'between':
         TextArgument.objects.create(validation=validation,
                                     position=0,
                                     param=self.cleaned_data['min_value'])
         TextArgument.objects.create(validation=validation,
                                     position=1,
                                     param=self.cleaned_data['max_value'])
     else:
         value = self.cleaned_data.get('value', '')
         if self.question.answer_type in [
                 MultiChoiceAnswer.choice_name(),
                 MultiSelectAnswer.choice_name()
         ]:
             value = self.cleaned_data['option']
         TextArgument.objects.create(validation=validation,
                                     position=0,
                                     param=value)
     # clean up now, remove all zombie questions
     self.question.qset.zombie_questions().delete()
예제 #38
0
def index(request, qset_id):
    # now I'm gonna call question set a batch of questions.\
    #If there's time, I'll rename them properly
    # So don't get confused :)
    try:
        batch = QuestionSet.get(pk=qset_id)
    except QuestionSet.DoesNotExist:
        raise Http404("No QuestionSet Model matches the given query.")
    questions = batch.questions_inline()
    request_data = request.GET if request.method == 'GET' else request.POST
    question_filter_form = QuestionFilterForm(data=request_data, qset=batch)
    search_fields = [
        'identifier',
        'text',
    ]
    qset_questions = batch.questions.all()
    if 'q' in request_data:
        questions = get_filterset(qset_questions, request_data['q'],
                                  search_fields)
    if 'question_types' in request_data:
        relevant_ids = list(
            question_filter_form.filter(qset_questions).values_list('id',
                                                                    flat=True))
        questions = [q for q in questions if q.id in relevant_ids]
    # now maintain same inline other exclusing questions in
    breadcrumbs = Question.index_breadcrumbs(qset=batch)
    if breadcrumbs:
        request.breadcrumbs(breadcrumbs)
    context = {
        'questions': questions,
        'request': request,
        'batch': batch,
        'question_filter_form': question_filter_form,
        'placeholder': 'identifier, text',
        'template_file': 'interviews/answer.html',
        'is_preview': True
        # caution atleast on ODK access
        #  at least on access must exist
    }
    return render(request, 'set_questions/index.html', context)
예제 #39
0
파일: views.py 프로젝트: samyhajal/survey
def create(request):
    post = request.POST
    question = Question(qu_text=post['text'], type=post['type'])
    question.save()
    return HttpResponseRedirect(reverse('all_questions', args=()))
예제 #40
0









#
#
# Here go questions:
#
#
q = Question()
q.code = 'q0'
q.type = info
q.text = 'This is q0. A start of everything. Literally...'
save(q)

q = Question()
q.code = 'q1'
q.type = info
q.text = 'Привет, исследователь! Надеюсь, твой гаджет хорошо заряжен, и в нем достаточно свободной памяти. Тебе предстоит сделать много фоток и нагулять хороший аппетит😄     Будь внимателен! Посмотри дважды, прежде чем ответить или сделать фото👀    Если сомневаешься, все равно фоткай. Да пребудет с тобой Сила Киноа!🙌'
save(q)

q = Question()
q.code = 'q2'
q.type = location
q.text = 'Нажми на кнопку, чтобы отправить геолокацию, и я узнаю, в каком ты сейчас магазине'
예제 #41
0
def get_sub_questions_for_question(request, question_id):
    question = Question.objects.get(id=question_id)
    return _create_question_hash_response(Question.zombies(question.batch))
예제 #42
0
def get_sub_questions_for_question(request, question_id):
    question = Question.objects.get(id=question_id)
    return _create_question_hash_response(Question.zombies(question.batch))
예제 #43
0
FILE_NAME = "QUESTIONS"

from survey.models import Question

f = open(FILE_NAME)

for line in f:
  line = line.strip()
  q = Question(qtext=line)
  q.save()


  
예제 #44
0
def assign(request, qset_id):
    batch = QuestionSet.get(id=qset_id)
    if batch.interviews.count():
        error_message = "Questions cannot be assigned \
            interviews has already been conducted: %s." % \
                        batch.name.capitalize()
        messages.error(request, error_message)
        return HttpResponseRedirect(
            reverse(
                'qset_questions_page',
                args=(
                    batch.pk,
                )))
    if request.method == 'POST':
        data = dict(request.POST)
        last_question = batch.last_question_inline()
        lib_questions = QuestionTemplate.objects.filter(
            identifier__in=data.get('identifier', ''))
        if lib_questions:
            for lib_question in lib_questions:
                question = Question.objects.create(
                    identifier=lib_question.identifier,
                    text=lib_question.text,
                    answer_type=lib_question.answer_type,
                    qset=batch,
                )
                # assign the options
                for option in lib_question.options.all():
                    QuestionOption.objects.create(
                        question=question,
                        text=option.text,
                        order=option.order)
                if last_question:
                    QuestionFlow.objects.create(
                        question=last_question, next_question=question)
                else:
                    batch.start_question = question
                    batch.save()
                last_question = question
            #batch_questions_form = BatchQuestionsForm(batch=batch,\
                #\data=request.POST, instance=batch)
        success_message = "Questions successfully assigned to %s: %s." % (
            batch.verbose_name(), batch.name.capitalize())
        messages.success(request, success_message)
        return HttpResponseRedirect(
            reverse(
                'qset_questions_page',
                args=(
                    batch.pk,
                )))
    used_identifiers = [
        question.identifier for question in batch.questions.all()]
    library_questions = QuestionTemplate.objects.exclude(
        identifier__in=used_identifiers).order_by('identifier')
    question_filter_form = QuestionFilterForm()
#     library_questions =  question_filter_form.filter(library_questions)
    breadcrumbs = Question.edit_breadcrumbs(qset=batch)
    page_name = ''
    if breadcrumbs:
        if breadcrumbs[0][0] == 'Listing Form':
            page_name = 'Listing'
        else:
            page_name = 'Batch'
        request.breadcrumbs(breadcrumbs)
    context = {
        'batch_questions_form': unicode(
            BatchQuestionsForm()),
        'batch': batch,
        'button_label': 'Save',
        'id': 'assign-question-to-batch-form',
        'library_questions': library_questions,
        'question_filter_form': question_filter_form,
        'page_name': page_name,
        'redirect_url': '/qsets/%s/questions/' % qset_id}
    return render(request, 'set_questions/assign.html',
                  context)
예제 #45
0
def assign(request, qset_id):
    batch = QuestionSet.get(id=qset_id)
    if batch.interviews.count():
        error_message = "Questions cannot be assigned \
            interviews has already been conducted: %s."                                                        % \
                        batch.name.capitalize()
        messages.error(request, error_message)
        return HttpResponseRedirect(
            reverse('qset_questions_page', args=(batch.pk, )))
    if request.method == 'POST':
        data = dict(request.POST)
        last_question = batch.last_question_inline()
        lib_questions = QuestionTemplate.objects.filter(
            identifier__in=data.get('identifier', ''))
        if lib_questions:
            for lib_question in lib_questions:
                question = Question.objects.create(
                    identifier=lib_question.identifier,
                    text=lib_question.text,
                    answer_type=lib_question.answer_type,
                    qset=batch,
                )
                # assign the options
                for option in lib_question.options.all():
                    QuestionOption.objects.create(question=question,
                                                  text=option.text,
                                                  order=option.order)
                if last_question:
                    QuestionFlow.objects.create(question=last_question,
                                                next_question=question)
                else:
                    batch.start_question = question
                    batch.save()
                last_question = question
            #batch_questions_form = BatchQuestionsForm(batch=batch,\
            #\data=request.POST, instance=batch)
        success_message = "Questions successfully assigned to %s: %s." % (
            batch.verbose_name(), batch.name.capitalize())
        messages.success(request, success_message)
        return HttpResponseRedirect(
            reverse('qset_questions_page', args=(batch.pk, )))
    used_identifiers = [
        question.identifier for question in batch.questions.all()
    ]
    library_questions = QuestionTemplate.objects.exclude(
        identifier__in=used_identifiers).order_by('identifier')
    question_filter_form = QuestionFilterForm()
    #     library_questions =  question_filter_form.filter(library_questions)
    breadcrumbs = Question.edit_breadcrumbs(qset=batch)
    page_name = ''
    if breadcrumbs:
        if breadcrumbs[0][0] == 'Listing Form':
            page_name = 'Listing'
        else:
            page_name = 'Batch'
        request.breadcrumbs(breadcrumbs)
    context = {
        'batch_questions_form': unicode(BatchQuestionsForm()),
        'batch': batch,
        'button_label': 'Save',
        'id': 'assign-question-to-batch-form',
        'library_questions': library_questions,
        'question_filter_form': question_filter_form,
        'page_name': page_name,
        'redirect_url': '/qsets/%s/questions/' % qset_id
    }
    return render(request, 'set_questions/assign.html', context)
예제 #46
0
def get_question_qa():
    current_term = _term.get_cur_term()
    areas = []
    groups = _checkpoint.get_project_cp_group_list(constant.current_project_id)
    for cp in groups:
        area = areaitem(cp.name, cp.desc)
        area.qas = _get_question_qa_by_cid(cp.name)
        area.qas.sort(lambda x, y:comparcid(x, y))
        if cp.name == 'G':
            question = Question()
            question.cid = 'G49b'
            question.title = u'有待改进的地方→'
            area.qas.insert(0, question)
            question = Question()
            question.cid = 'G49a'
            question.title = u'做得比较好的地方→'
            area.qas.insert(0, question)
            question = Question()
            question.cid = ''
            question.title = u'除了以上这些评价的问题之外,经销商的表现有没有您认为做得比较好的地方或有待改进的地方?'
            area.qas.insert(0, question)
            
        areas.append(area)
    return areas, current_term
예제 #47
0
#
#

yes_no_cats = lambda: [
    Category(text=emojize('Да :smile:')),
    Category(text=emojize('Нет :pensive:'))
]

three_scale_cats = lambda: [
    Category(text=emojize('Да, все четко! :thumbsup:')),
    Category(text=emojize('На троечку, порядка не хватает :grin:')),
    Category(text=emojize('Все плохо, хочется убежать :scream:'))
]


q = Question()
q.code = 'q1'
q.type = types.info
q.text = emojize('Привет, исследователь! Надеюсь, твой гаджет хорошо заряжен, и в нем достаточно свободной памяти.\nТебе предстоит сделать много фоток и нагулять хороший аппетит :smile: \nБудь внимателен! Посмотри дважды, прежде чем ответить или сделать фото :eyes: \nЕсли сомневаешься, все равно фоткай. Да пребудет с тобой Сила Киноа! :raised_hands:')
save(q)

q = Question()
q.code = 'q2'
q.type = types.location
q.text = emojize('Нажми на кнопку, чтобы отправить геолокацию, и я узнаю, в каком ты сейчас магазине :round_pushpin:')
cats = [Category(text='Отправить местоположение'), ]
q.categories = cats
save(q)


q = Question()