Пример #1
0
    def test_creator_num_answers(self):
        question = Question.objects.all()[0]
        answer = Answer(question=question, creator_id=47963,
                        content="Test Answer")
        answer.save()

        eq_(answer.creator_num_answers, 2)
Пример #2
0
def update(request, id):
    if request.method != 'POST':
        return return_json(post_error, 400)


    question_text, answers, correct_index = edit_post_vars(request)

    q = Question.objects.get(pk=id)
    q.question = question_text
    q.save()

    q.answer_set.all().delete()

    i=0;
    for answer in answers:
        a = Answer(question=q, choice=answer, correct=(i == correct_index))
        a.save()
        i += 1

    data = {
        'result': 'success',
        'id': id,
    }
    json_result = json.JSONEncoder().encode(data)
    return return_json(json_result)
Пример #3
0
    def test_percent(self, switch_is_active):
        """Test user API with all defaults."""
        switch_is_active.return_value = True
        u = user()
        u.save()
        add_permission(u, Profile, 'view_kpi_dashboard')
        question = Question(title='Test Question',
                            content='Lorem Ipsum Dolor',
                            creator_id=u.id)
        question.save()
        answer = Answer(question=question, creator_id=u.id,
                        content="Test Answer")
        answer.save()

        question.solution = answer
        question.save()

        url = reverse('api_dispatch_list',
                      kwargs={'resource_name': 'kpi_solution',
                              'api_name': 'v1'})
        self.client.login(username=u.username, password='******')
        response = self.client.get(url + '?format=json')
        eq_(200, response.status_code)
        r = json.loads(response.content)
        eq_(r['objects'][0]['with_solutions'], 1)
        eq_(r['objects'][0]['without_solutions'], 0)
Пример #4
0
 def create_answer(self, name):
     question = Question.objects.order_by("?")[:1][0]
     author = UserWithAvatar.objects.order_by("?")[:1][0]
     pub_date = timezone.now()
     text = self.lorem
     answer = Answer(question=question, author=author, pub_date=pub_date, text=text)
     answer.save()
Пример #5
0
    def test_form_should_post_proper_data_via_signal(self):
        """ test signal sending message if added a comment """
        mock_handler = MagicMock()

        user = User.objects.create_user(username='******',
                                        email='*****@*****.**',
                                        password='******')
        user.save()
        question = Question(title='test_title',
                            question='asasdasdas',
                            owner_id=1)
        question.save()
        answer = Answer(answer_text='some_text', answers_question=question)
        answer.save()

        signals.post_save.connect(mock_handler, sender=Answer)

        signals.post_save.send(sender=Answer,
                               instance=question,
                               answer=answer.answer_text)

        # handler.assert_called_once_with(
        #                                  signal=signals.post_save.send,
        #                                  sender=Answer,
        #                                  instance=question,
        #                                  answer=answer.answer_text)
        self.assertEquals(mock_handler.call_count, 1)
Пример #6
0
    def test_creator_num_answers(self):
        question = Question.objects.all()[0]
        answer = Answer(question=question,
                        creator_id=47963,
                        content="Test Answer")
        answer.save()

        eq_(answer.creator_num_answers, 2)
Пример #7
0
def create_answers_for_questions():
    f = Faker()
    for i in Question.objects.all():
        for j in range(random.randint(1, 4)):
            answer = Answer(question_id=i,
                            authtor_id=User.objects.all()[random.randint(
                                1,
                                User.objects.count() - 1)],
                            text=f.text(300),
                            is_correct=False)
            answer.save()
Пример #8
0
    def test_creator_num_answers(self):
        """Test retrieval of answer count for creator of a particular answer"""
        question = Question.objects.all()[0]
        answer = Answer(question=question, creator_id=47963,
                        content="Test Answer")
        answer.save()

        question.solution = answer
        question.save()

        eq_(answer.creator_num_answers, 1)
Пример #9
0
def post_answer(request, question_id):
    q = Question.objects.get(pk=question_id)
    u = User.objects.get(pk=1)
    content = request.POST.get('content')
    a = Answer(content=content,
               author=u,
               pub_date=timezone.now(),
               votes=0,
               question_id=question_id)
    a.save()
    return detail(request, question_id)
Пример #10
0
    def test_creator_num_answers(self):
        """Test retrieval of answer count for creator of a particular answer"""
        question = Question.objects.all()[0]
        answer = Answer(question=question,
                        creator_id=47963,
                        content="Test Answer")
        answer.save()

        question.solution = answer
        question.save()

        eq_(answer.creator_num_answers, 1)
Пример #11
0
    def post(self, request, *args, **kwargs):
        survey = Survey.objects.filter(id=self.kwargs['pk']).first()

        for question_id, option_id in request.POST.items():
            if question_id.isdigit():
                question = Question.objects.filter(id=question_id).first()
                option = Option.objects.filter(id=option_id).first()
                if question and option:
                    answer = Answer(option=option, user=None if request.user.is_anonymous() else request.user)
                    answer.save()

        return HttpResponseRedirect("/survey/%d/results/" %(survey.id))
Пример #12
0
 def handle(self, *args, **options):
     for i in range(1, 20):
         u = User.objects.get(id=1)
         t = Tag.objects.get(word='test_tag')
         titlename= 'Test Question ' + str(i)
         exampletext = 'Examples of closed-ended questions are: Are you feeling better today? May I use the bathroom? Is the prime rib a special tonight?'
         q = Question(author = u, title = titlename, text = exampletext, rating = random.randint(-10, 10), date = datetime.now())
         q.save()
         q.tags.add(t)
         exampleanswer = 'Closed-ended questions should not always be thought of as simple questions that anyone can quickly answer merely because they require a yes or no answer. '
         a = Answer(question_id=q.id, author = u, text = exampleanswer, rating = random.randint(-10, 10), date = datetime.now(), correct=False)
         a.save()
         self.stdout.write(self.style.SUCCESS('Successfully added item "%s"' % i))
Пример #13
0
def create_answer(question, tiki_post, tiki_thread):
    """Create an answer to a question from a Tiki post."""
    creator = get_django_user(tiki_post)
    created = datetime.fromtimestamp(tiki_post.commentDate)
    content = converter.convert(tiki_post.data)

    ans = Answer(question=question, creator=creator, content=content, created=created, updated=created)
    ans.save(no_update=True, no_notify=True)  # don't send a reply notification

    # Set answer as solution
    if tiki_post.type == "o" and tiki_thread.type == "o":
        question.solution = ans

    return ans
Пример #14
0
 def post(self, request, question_id):
     form = AnswerForm(request.POST)
     if form.is_valid():
         answer = Answer(
             text=form.cleaned_data["text"],
             question_id=question_id,
             author=request.user,
         )
         answer.save()
         return redirect("question", question_id)
     context = {
         'answer_form': form,
     }
     return render(request, 'questions/question.html', context)
Пример #15
0
def answerView(request, id):
    current_user = request.user

    if not current_user.is_authenticated:
        return HttpResponseRedirect('/accounts/login')
    if not request.method == 'POST':
        return HttpResponseRedirect(f'/question/{id}')
    form = AnswerForm(request.POST)
    if not form.is_valid():
        return HttpResponseRedirect(f'/question/{id}')
    a = Answer(user_id=current_user.id,
               question_id=id,
               text=form.cleaned_data['text'])
    a.save()
    return HttpResponseRedirect(f'/question/{id}')
Пример #16
0
def answer_preview_async(request):
    """Create an HTML fragment preview of the posted wiki syntax."""
    statsd.incr('questions.preview')
    answer = Answer(creator=request.user,
                    content=request.POST.get('content', ''))
    return jingo.render(request, 'questions/includes/answer_preview.html',
                        {'answer_preview': answer})
Пример #17
0
async def answer_create(request):
    """
    Answer form
    """
    id = int(request.query_params['next'].split('/')[2])
    next = request.query_params['next']
    results = (
        await Question.get(id=id)
        .prefetch_related("user", "tags")
    )
    session_user = request.user.username
    data = await request.form()
    form = AnswerForm(data)
    result = await User.get(username=session_user)
    if request.method == "POST" and form.validate():
        query = Answer(
            content=form.content.data,
            created=datetime.datetime.now(),
            answer_like=0,
            is_accepted_answer=0,
            question_id=results.id,
            ans_user_id=result.id,
        )
        await query.save()
        return RedirectResponse(BASE_HOST + next, status_code=302)
    return templates.TemplateResponse(
        "questions/answer_create.html", {
            "request": request,
            "form": form,
            "next": next
        }
    )
    def handle(self, *args, **options):
        i = 0
        k = 0
        n = int(args[0])
        allusers = UserProfile.objects.all()
        tags = Tag.objects.all()
        while i < n:
            titleNumber = random.randint(0, 50)
            textNumber = random.randint(0, 300)
            rate = random.randint(-100, 100)
            number = random.randint(0, 10)

            numberOfTags = random.randint(0, 5)
            tagsList = []
            for q in range(0, numberOfTags):
                randomTag = random.randint(0, len(tags) - 1)
                tagsList.insert(q, tags[randomTag])

            title = "".join(
                random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits + string.whitespace)
                for x in range(titleNumber)
            )
            token = "".join(
                random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits + string.whitespace)
                for x in range(textNumber)
            )
            i = i + 1

            randomUserId = random.randint(0, len(allusers) - 1)
            user = allusers[randomUserId]

            q = Question(title=title, text=token, rate=rate, author=user)
            q.save()
            q.tags.add(*tagsList)

            for j in range(0, number):
                randomUserId = random.randint(0, len(allusers) - 1)
                userComment = allusers[randomUserId]
                rateComment = random.randint(-100, 100)
                textComment = random.randint(0, 300)
                text = "".join(
                    random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits + string.whitespace)
                    for x in range(textComment)
                )
                k = k + 1
                a = Answer(k, text=text, rate=rateComment, answers_question=q, author=userComment)
                a.save()
Пример #19
0
def apply_answer(question, answer, user):
    try:
        a = Answer.objects.get(question=question, user=user)
    except:
        if answer != '0':
            a = Answer(question=question, user=user, answer=answer)
            a.save()
    else:
        if answer == '0':
            a.delete()
        else:
            a.answer = answer
            a.save()
Пример #20
0
    def test_creator_num_posts(self):
        """Test retrieval of post count for creator of a particular answer"""
        question = Question.objects.all()[0]
        answer = Answer(question=question,
                        creator_id=47963,
                        content="Test Answer")

        eq_(answer.creator_num_posts, 4)
Пример #21
0
def answer(**kwargs):
    defaults = dict(created=datetime.now(), content='', upvotes=0)
    defaults.update(kwargs)
    if 'question' not in kwargs and 'question_id' not in kwargs:
        defaults['question'] = question(save=True)
    if 'creator' not in kwargs and 'creator_id' not in kwargs:
        defaults['creator'] = user(save=True)
    return Answer(**defaults)
Пример #22
0
 def handle(self, *args, **options):
     #users=['Ram','Shayam','Somesh']
     answers = ['Hyderabad', 'Islamabad', 'Delhi']
     for each in range(100):
         answer = random.choice(answers)
         #answerd_user=random.choice(users)
         data = Answer.objects.bulk_create([Answer(answer=answer)])
     print("{} answers inserted Succesfully!".format(each))
Пример #23
0
    def test_delete_answer_removes_flag(self):
        """Deleting an answer also removes the flags on that answer."""
        question = Question(title='Test Question',
                            content='Lorem Ipsum Dolor',
                            creator_id=118533)
        question.save()

        answer = Answer(question=question, creator_id=47963,
                        content="Test Answer")
        answer.save()

        FlaggedObject.objects.create(
            status=0, content_object=answer,
            reason='language', creator_id=118533)
        eq_(1, FlaggedObject.objects.count())

        answer.delete()
        eq_(0, FlaggedObject.objects.count())
Пример #24
0
def answer_create(request):
    
    if request.method == 'POST':
        try:
            answer = request.POST.get('answer')
            qid = request.POST.get('question')
            question = Question.objects.get(id=qid)
            if request.user.id ==question.author_id:
                messages.success(request, f'You Can not answer your own question!',extra_tags='warning')
            else:
                user  = request.user
                answer =Answer(author=user,question=question,answer=answer)
                answer.save()
                messages.success(request, f'Your Answer Posted!',extra_tags='success')
        except:
            # print
            messages.success(request, f'Something went wrong!',extra_tags='error')
       
    return redirect('questions-detail', pk=qid)
Пример #25
0
def reply(request, question_id):
    """Post a new answer to a question."""
    question = get_object_or_404(Question, pk=question_id)
    answer_preview = None
    if question.is_locked:
        raise PermissionDenied

    form = AnswerForm(request.POST)

    # NOJS: delete images
    if 'delete_images' in request.POST:
        for image_id in request.POST.getlist('delete_image'):
            ImageAttachment.objects.get(pk=image_id).delete()

        return answers(request, question_id, form)

    # NOJS: upload image
    if 'upload_image' in request.POST:
        upload_imageattachment(request, question)
        return answers(request, question_id, form)

    if form.is_valid():
        answer = Answer(question=question,
                        creator=request.user,
                        content=form.cleaned_data['content'])
        if 'preview' in request.POST:
            answer_preview = answer
        else:
            answer.save()
            ct = ContentType.objects.get_for_model(answer)
            # Move over to the answer all of the images I added to the
            # reply form
            up_images = question.images.filter(creator=request.user)
            up_images.update(content_type=ct, object_id=answer.id)
            statsd.incr('questions.answer')

            if Setting.get_for_user(request.user,
                                    'questions_watch_after_reply'):
                QuestionReplyEvent.notify(request.user, question)

            return HttpResponseRedirect(answer.get_absolute_url())

    return answers(request, question_id, form, answer_preview=answer_preview)
Пример #26
0
def reply(request, question_id):
    """Post a new answer to a question."""
    question = get_object_or_404(Question, pk=question_id)
    answer_preview = None
    if question.is_locked:
        raise PermissionDenied

    form = AnswerForm(request.POST)

    # NOJS: delete images
    if 'delete_images' in request.POST:
        for image_id in request.POST.getlist('delete_image'):
            ImageAttachment.objects.get(pk=image_id).delete()

        return answers(request, question_id=question_id, form=form)

    # NOJS: upload image
    if 'upload_image' in request.POST:
        upload_imageattachment(request, question)
        return answers(request, question_id=question_id, form=form)

    if form.is_valid():
        answer = Answer(question=question, creator=request.user,
                        content=form.cleaned_data['content'])
        if 'preview' in request.POST:
            answer_preview = answer
        else:
            answer.save()
            ct = ContentType.objects.get_for_model(answer)
            # Move over to the answer all of the images I added to the
            # reply form
            up_images = question.images.filter(creator=request.user)
            up_images.update(content_type=ct, object_id=answer.id)
            statsd.incr('questions.answer')

            if Setting.get_for_user(request.user,
                                    'questions_watch_after_reply'):
                QuestionReplyEvent.notify(request.user, question)

            return HttpResponseRedirect(answer.get_absolute_url())

    return answers(request, question_id=question_id, form=form,
                   answer_preview=answer_preview)
Пример #27
0
    def test_delete_last_answer_of_question(self):
        """Deleting the last_answer of a Question should update the question.
        """
        question = Question.objects.get(pk=1)
        last_answer = question.last_answer

        # add a new answer and verify last_answer updated
        answer = Answer(question=question, creator_id=47963,
                        content="Test Answer")
        answer.save()
        question = Question.objects.get(pk=question.id)

        eq_(question.last_answer.id, answer.id)

        # delete the answer and last_answer should go back to previous value
        answer.delete()
        question = Question.objects.get(pk=question.id)
        eq_(question.last_answer.id, last_answer.id)
        eq_(Answer.objects.filter(pk=answer.id).count(), 0)
Пример #28
0
def insert_question(request):
    context = dict()
    if request.method == 'POST':
        question_text = request.POST['question']
        exam_id = request.POST['exam']
        exam = get_object_or_404(Exam, pk=exam_id)
        question = Question(question_text=question_text, exam=exam)
        question.save()
        for i in range(1, 5):
            answer_text = request.POST['answer' + str(i)]
            correct = int(request.POST['correct']) == i
            answer = Answer(answer_text=answer_text,
                            correct=correct,
                            question=question)
            answer.save()
        context['inserted'] = True
        context['last_exam'] = exam_id
    exams = Exam.objects.all()
    context['exams'] = exams
    return render(request, 'questions/insert_question.html', context)
Пример #29
0
    def test_new_answer_updates_question(self):
        """Test saving a new answer updates the corresponding question.
        Specifically, last_post and num_replies should update."""
        question = Question(title='Test Question',
                            content='Lorem Ipsum Dolor',
                            creator_id=118533)
        question.save()

        eq_(0, question.num_answers)
        eq_(None, question.last_answer)

        answer = Answer(question=question, creator_id=47963,
                        content="Test Answer")
        answer.save()

        question = Question.objects.get(pk=question.id)
        eq_(1, question.num_answers)
        eq_(answer, question.last_answer)

        question.delete()
Пример #30
0
def apply_answer(question, answer, user):
    try:
        a = Answer.objects.get(question=question, user=user)
    except:
        if answer != "0":
            a = Answer(question=question, user=user, answer=answer)
            a.save()
    else:
        if answer == "0":
            a.delete()
        else:
            a.answer = answer
            a.save()
Пример #31
0
def new(request):
    if request.method != 'POST':
        return return_json(post_error)

    question_text, answers, correct_index = edit_post_vars(request)

    q = Question(question=question_text)
    q.save()

    i = 0;
    for answer in answers:
        a = Answer(question=q, choice=answer, correct=(i == correct_index))
        a.save()
        i += 1

    data = {
        'result': 'success',
        'id': q.id
    }
    json_result = json.JSONEncoder().encode(data)
    return HttpResponse(json_result, content_type="application/json")
Пример #32
0
    def test_new_answer_updates_question(self):
        """Test saving a new answer updates the corresponding question.
        Specifically, last_post and num_replies should update."""
        question = Question(title='Test Question',
                            content='Lorem Ipsum Dolor',
                            creator_id=118533)
        question.save()

        eq_(0, question.num_answers)
        eq_(None, question.last_answer)

        answer = Answer(question=question,
                        creator_id=47963,
                        content="Test Answer")
        answer.save()

        question = Question.objects.get(pk=question.id)
        eq_(1, question.num_answers)
        eq_(answer, question.last_answer)

        question.delete()
Пример #33
0
def login():
    uname = request.form['user_name']
    if db.session.query(Answer).filter(Answer.user_name == uname).count():
        flash('おかえりなさい' + uname + 'さん')
    else:
        answer = Answer(user_name=uname, ip=request.remote_addr)
        for i in range(app.config['BRANCH_NUMBER']):
            exec('answer.branch%d = branchAB()' % (i))
        db.session.add(answer)
        db.session.commit()
        flash('こんにちは' + uname + 'さん')
    session.pop('user_name', None)
    session['user_name'] = uname
    return redirect(url_for('question'))
Пример #34
0
    def fill_answers(self):
        fake = Factory.create()

        min_number = 10
        max_number = 20


        questions = Question.objects.all()
        is_correct = (True, False)
        counter = 1
        for q in questions:
            for i in range(0, randint(min_number, max_number)):
                ans = Answer()

                ans.text = fake.paragraph(nb_sentences=randint(2, 4), variable_nb_sentences=True)
                ans.author = Profile.objects.first()
                ans.question = q
                ans.rating = randint(0, 1500)
                ans.is_correct = choice(is_correct)
                ans.id = counter
                counter += 1
                ans.save()
                self.stdout.write('in question [%d] add ans [%d]' % (q.id, ans.id))
Пример #35
0
    def add_answer_to_db(self, tweet):
        question = Question.objects.get_current_question()
        person = Person.objects.filter(twitter_username=tweet.user.screen_name)

        #TODO: could this sort of logic be moved to the model?
        if not person:
            # Get the users real name
            user = self.twitter_api.GetUser(tweet.user.screen_name)
            full_name_list = user.name.split(" ")
            first_name = full_name_list[0]
            middle_names = " ".join(full_name_list[1:-1])
            if len(full_name_list) > 1:
                surname = full_name_list[-1]
            else:
                surname = ""

            person = Person(twitter_username=tweet.user.screen_name,
                first_name=first_name,
                middle_names=middle_names,
                surname=surname)
            person.save()
        else:
            # get person from the query set.
            # Inelegant could this be modified with custom save() on the model?
            person = person[0]

        # Remove @FavouriteQueston from the tweet (+2 is for @ and space)
        answer_text = tweet.text[len(self.twitter_account) + 2:]
        # Decode HTML encoded entities from Twitter
        h = HTMLParser.HTMLParser()
        answer_text = h.unescape(answer_text)

        a = Answer(answer_text=answer_text,
                   person=person,
                   question=question,
                   tweet_id=tweet.id)
        a.save()
Пример #36
0
    def add_answer_to_db(self, tweet):
        question = Question.objects.get_current_question()
        person = Person.objects.filter(twitter_username=tweet.user.screen_name)

        #TODO: could this sort of logic be moved to the model?
        if not person:
            # Get the users real name
            user = self.twitter_api.GetUser(tweet.user.screen_name)
            full_name_list = user.name.split(" ")
            first_name = full_name_list[0]
            middle_names = " ".join(full_name_list[1:-1])
            if len(full_name_list) > 1:
                surname = full_name_list[-1]
            else:
                surname = ""

            person = Person(twitter_username=tweet.user.screen_name,
                            first_name=first_name,
                            middle_names=middle_names,
                            surname=surname)
            person.save()
        else:
            # get person from the query set.
            # Inelegant could this be modified with custom save() on the model?
            person = person[0]

        # Remove @FavouriteQueston from the tweet (+2 is for @ and space)
        answer_text = tweet.text[len(self.twitter_account) + 2:]
        # Decode HTML encoded entities from Twitter
        h = HTMLParser.HTMLParser()
        answer_text = h.unescape(answer_text)

        a = Answer(answer_text=answer_text,
                   person=person,
                   question=question,
                   tweet_id=tweet.id)
        a.save()
Пример #37
0
def comment(request, id):
    comment_form = CommentForm(request.POST or None)
    args = {}
    args['form'] = comment_form

    if request.POST and comment_form.is_valid():
        user = auth.get_user(request)
        a = Question.objects.all().filter(id=id)

        answer = Answer(text=comment_form.cleaned_data['text'])
        answer.author = user
        answer.answers_question=a[0]
        answer.save()

        # sending mail
        str = "User " + user.username + " answer your question " + a[0].title + "\n" + \
                  "Text: " + answer.text
        send_mail('New Comment!', str, '*****@*****.**', [a[0].author.email], fail_silently=False)

        # return redirect('questionGet' + '#text', question_id=a[0].id)
        return redirect('/question/get/%s#text' % id)
    else:
        return redirect('/question/get/%s#text' % id)
    return render(request, 'question_render.html', args)
Пример #38
0
    def setUp(self):
        user = User(username='******')
        user.save()
        o1 = Organisation(name='Organisation 1')
        o1.user = user
        o1.save()

        user = User(username='******')
        user.save()
        o2 = Organisation(name='Organisation 2')
        o2.user = user
        o2.save()

        c1 = Candidate(popit_id=1235,
                       name='Bob',
                       contact_address='*****@*****.**',
                       participating=True)
        c1.save()
        self.candidate = c1

        q1 = Question(
            organisation=o1,
            question='What is your name?',
            type='text',
        )
        q1.save()
        q2 = Question(
            organisation=o2,
            question='What is your quest?',
            type='text',
        )
        q2.save()

        a1 = Answer(candidate=c1,
                    question=q1,
                    completed=True,
                    completed_timestamp=datetime.datetime(
                        2015, 1, 1, tzinfo=timezone.get_current_timezone()))
        a1.save()
        self.a1 = a1

        a2 = Answer(candidate=c1, question=q2, completed=False)
        a2.save()
        self.a2 = a2
Пример #39
0
    def create_answers(self):
        faker = Faker()

        question_set = Question.objects.all()
        author_set = User.objects.all()

        for i in range(100):
            answer = Answer()
            answer.author = random.choice(author_set)
            answer.question = random.choice(question_set)
            answer.text = faker.text(max_nb_chars=200, ext_word_list=None)
            try:
                answer.save()
            except:
                print("Answer repeated")
Пример #40
0
    def handle(self, *args, **options):
        fake_factory = Factory.create('en_US')

        min_number = int(options['min_number'])
        max_number = int(options['max_number'])

        users = User.objects.all()[1:]
        questions = Question.objects.all()

        for question in questions:
            for i in range(randint(min_number, max_number)):
                answer = Answer()

                answer.text = fake_factory.paragraph(nb_sentences=randint(2, 10), variable_nb_sentences=True)
                answer.author = choice(users)
                answer.question = question
                answer.date = fake_factory.date()
                answer.save()
                self.stdout.write('[%d] ans[%d]' % (question.id, answer.id))
Пример #41
0
    def test_delete_answer_removes_flag(self):
        """Deleting an answer also removes the flags on that answer."""
        question = Question(title='Test Question',
                            content='Lorem Ipsum Dolor',
                            creator_id=118533)
        question.save()

        answer = Answer(question=question, creator_id=47963,
                        content="Test Answer")
        answer.save()

        FlaggedObject.objects.create(
            status=0, content_object=answer,
            reason='language', creator_id=118533)
        eq_(1, FlaggedObject.objects.count())

        answer.delete()
        eq_(0, FlaggedObject.objects.count())
Пример #42
0
def answer(request):
    if request.method == 'POST':
        form = AnswerForm(request.POST)
        if form.is_valid():
            user = request.user
            answer = Answer()
            answer.user = request.user
            answer.question = form.cleaned_data.get('question')
            answer.description = form.cleaned_data.get('description')
            answer.save()
            user.profile.notify_answered(answer.question)
            return redirect(u'/questions/{0}/'.format(answer.question.pk))
        else:
            question = form.cleaned_data.get('question')
            return render(request, 'questions/question.html', {'question': question, 'form': form})
    else:
        return redirect('/questions/')
Пример #43
0
    def test_delete_last_answer_of_question(self):
        """Deleting the last_answer of a Question should update the question.
        """
        question = Question.objects.get(pk=1)
        last_answer = question.last_answer

        # add a new answer and verify last_answer updated
        answer = Answer(question=question, creator_id=47963,
                        content="Test Answer")
        answer.save()
        question = Question.objects.get(pk=question.id)

        eq_(question.last_answer.id, answer.id)

        # delete the answer and last_answer should go back to previous value
        answer.delete()
        question = Question.objects.get(pk=question.id)
        eq_(question.last_answer.id, last_answer.id)
        eq_(Answer.objects.filter(pk=answer.id).count(), 0)
Пример #44
0
def users(request):
    """Returns list of user karma information.

    GET paramaters:
    * daterange - 7d, 1m, 3m, 6m or 1y (default: 1y)
    * sort - field to sort on (default: points). Order is always descending.
    * page - starts at 1 (default: 1)
    * pagesize - (default: 100)

    Returns list of objects with the following fields:
        userid, username, points, <action_types>
    """
    form = UserAPIForm(request.GET)
    if not form.is_valid():
        return {'success': False, 'errors': form.errors}

    daterange = form.cleaned_data.get('daterange') or '1y'
    sort = form.cleaned_data.get('sort') or 'points'
    page = form.cleaned_data.get('page') or 1
    pagesize = form.cleaned_data.get('pagesize') or 100

    mgr = KarmaManager()
    users = mgr.top_users(daterange=daterange, type=sort, count=pagesize,
                          offset=(page - 1) * pagesize) or []

    now = datetime.now()
    action_types = KarmaManager.action_types.keys()
    schema = ['id', 'username', 'lastactivity', 'points'] + action_types
    user_list = []
    for u in users:
        user = [u.id, u.username]
        last_activity = Answer.last_activity_for(u)
        user.append((now - last_activity).days if last_activity else None)
        user.append(mgr.count(u, daterange=daterange, type='points'))
        for t in action_types:
            user.append(mgr.count(u, daterange=daterange, type=t))
        user_list.append(user)

    return {
        'success': True,
        'results': user_list,
        'schema': schema}
Пример #45
0
def users(request):
    """Returns list of user karma information.

    GET paramaters:
    * daterange - 7d, 1m, 3m, 6m or 1y (default: 1y)
    * sort - field to sort on (default: points). Order is always descending.
    * page - starts at 1 (default: 1)
    * pagesize - (default: 100)

    Returns list of objects with the following fields:
        userid, username, points, <action_types>
    """
    form = UserAPIForm(request.GET)
    if not form.is_valid():
        return {'success': False, 'errors': form.errors}

    daterange = form.cleaned_data.get('daterange') or '1y'
    sort = form.cleaned_data.get('sort') or 'points'
    page = form.cleaned_data.get('page') or 1
    pagesize = form.cleaned_data.get('pagesize') or 100

    mgr = KarmaManager()
    users = mgr.top_users(daterange=daterange,
                          type=sort,
                          count=pagesize,
                          offset=(page - 1) * pagesize) or []

    now = datetime.now()
    action_types = KarmaManager.action_types.keys()
    schema = ['id', 'username', 'lastactivity', 'points'] + action_types
    user_list = []
    for u in users:
        user = [u.id, u.username]
        last_activity = Answer.last_activity_for(u)
        user.append((now - last_activity).days if last_activity else None)
        user.append(mgr.count(u, daterange=daterange, type='points'))
        for t in action_types:
            user.append(mgr.count(u, daterange=daterange, type=t))
        user_list.append(user)

    return {'success': True, 'results': user_list, 'schema': schema}
Пример #46
0
def get_api_answers(request):
    """
    :param request: HTTP request
    :return: one page with answers to the question in json format
    """
    question_id = request.GET.get('question_id')
    if not question_id:
        return HttpResponse(content=json.dumps({"error": "no id in request"}),
                            status=HTTPStatus.BAD_REQUEST)

    answers, page, *_ = Answer.get_answers_page(request)
    serialized_answers = AnswerSerializer(answers, many=True)
    return HttpResponse(
        json.dumps(
            {
                "question_id": question_id,
                "page": page,
                'has next': answers.has_next(),
                'has prev': answers.has_previous(),
                "answers": serialized_answers.data
            },
            indent=4))
Пример #47
0
def answer(request):
    if request.method == 'POST':
        form = AnswerForm(request.POST)
        if form.is_valid():
            user = request.user
            answer = Answer()
            answer.user = request.user
            answer.question = form.cleaned_data.get('question')
            answer.description = form.cleaned_data.get('description')
            answer.save()
            user.profile.notify_answered(answer.question)
            return redirect(u'/questions/{0}/'.format(answer.question.pk))
        else:
            question = form.cleaned_data.get('question')
            return render(request, 'questions/question.html', {'question': question, 'form': form})
    else:
        return redirect('/questions/')
Пример #48
0
def users(request):
    """Returns list of user karma information.

    GET paramaters:
    * daterange - 7d, 1m, 3m, 6m or 1y (default: 1y)
    * sort - field to sort on (default: points). Order is always descending.
    * page - starts at 1 (default: 1)
    * pagesize - (default: 100)

    Returns list of objects with the following fields:
        userid, username, points, <action_types>
    """
    form = UserAPIForm(request.GET)
    if not form.is_valid():
        return {"success": False, "errors": form.errors}

    daterange = form.cleaned_data.get("daterange") or "1y"
    sort = form.cleaned_data.get("sort") or "points"
    page = form.cleaned_data.get("page") or 1
    pagesize = form.cleaned_data.get("pagesize") or 100

    mgr = KarmaManager()
    users = mgr.top_users(daterange, type=sort, count=pagesize, offset=(page - 1) * pagesize) or []

    now = datetime.now()
    action_types = KarmaManager.action_types.keys()
    schema = ["id", "username", "lastactivity", "points"] + action_types
    user_list = []
    for u in users:
        user = [u.id, u.username]
        last_activity = Answer.last_activity_for(u)
        user.append((now - last_activity).days if last_activity else None)
        user.append(mgr.count(daterange, u, type="points"))
        for t in action_types:
            user.append(mgr.count(daterange, u, type=t))
        user_list.append(user)

    return {"success": True, "results": user_list, "schema": schema}
Пример #49
0
async def answer_create(request):
    """
    Answer form
    """
    id = request.path_params["id"]
    session_user = request.user.username
    form = await request.json()
    content = form["content"]
    result = await User.get(username=session_user)
    results = await Question.get(id=id)
    if request.method == "POST":
        query = Answer(
            content=content,
            created=datetime.datetime.now(),
            answer_like=0,
            is_accepted_answer=0,
            question_id=results.id,
            ans_user_id=result.id,
        )
        await query.save()
        results.answer_count += 1
        await results.save()
        return RedirectResponse(url="/questions/", status_code=303)
Пример #50
0
    def handle(self, *args, **options):

        Question.objects.all().delete()
        Answer.objects.all().delete()
        print('Deleted existing data')


        with open(settings.BASE_DIR + '/../' + self.csv_file, 'r') as csvfile:
            reader = csv.reader(csvfile, delimiter='|')
            next(reader, None)
            for row in reader:

                q = Question(question=row[0])
                q.save()
                print('Saved question with id ' + str(q.id));

                a = Answer(question=q, choice=row[1], correct=True)
                a.save()

                for i in row[2].split(','):
                    aw = Answer(question=q, choice=i, correct=False)
                    aw.save()
Пример #51
0
    def doimport(self,data):

        from django.contrib.auth.models import User
        from questions.models import Question, Answer
        from tagging.models import Tag
    
        try:
            question = Question()
            question.content = data['question']
            question.tags = data['tags']
            question.author = User.objects.get(pk=0) #FIXME: System smrtr user: use constant?
            question.save() # Save to allow m2m

            # Create correct answer
            c = Answer()
            c.content = data['correct']
            c.is_correct = True
            c.question = question
            c.save()
            
            # Save incorrect answers
            data['incorrect'] = filter(lambda x: len(x)>0, data['incorrect']) # Remove empty items
            for incorrect in data['incorrect']:
                ic = Answer()
                ic.content = incorrect
                ic.is_correct = False
                ic.question = question
                ic.save()
        except:
            print "Error importing:" + data['question']