Ejemplo n.º 1
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']
Ejemplo n.º 2
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)
Ejemplo n.º 3
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)
Ejemplo n.º 4
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
        }
    )
Ejemplo n.º 5
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})
Ejemplo n.º 6
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)
Ejemplo n.º 7
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)
Ejemplo n.º 8
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))
Ejemplo n.º 9
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
Ejemplo n.º 10
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)
Ejemplo n.º 11
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()
Ejemplo n.º 12
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)
Ejemplo n.º 13
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()
Ejemplo n.º 14
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))
Ejemplo n.º 15
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)
Ejemplo n.º 16
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'))
Ejemplo n.º 17
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}')
Ejemplo n.º 18
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")
Ejemplo n.º 19
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/')
Ejemplo n.º 20
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())
Ejemplo n.º 21
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)
Ejemplo n.º 22
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)
Ejemplo n.º 23
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)
Ejemplo n.º 24
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))
Ejemplo n.º 25
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)
Ejemplo n.º 26
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()
Ejemplo n.º 27
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))
Ejemplo n.º 28
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)
Ejemplo n.º 29
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()
Ejemplo n.º 30
0
    def generate_questions_answers():
        question_titles = ['How to do Web homework?',
                           'What is the capital of Chezh Republic?',
                           'Why everybody likes Joker?',
                           'What is decorator?',
                           'How to add a question on this site?',
                           'How to run a command?',
                           'How to choose fonts for a site?',
                           'How to create a django project?',
                           'How to move model managers to another file?',
                           'How to reset a commit without deleting files?',
                           'How to do sorting in multiple threads?']
        question_texts = ['Really, how?',
                          'I have a homework at school and my teacher doesn\'t know',
                          'I can\'t decide whether to go to the cinema or not',
                          'Explain please',
                          'The only way I found is to enter path \'ask-alice/ask\' but there should have been '
                          'another way...',
                          'I\'ve written a command in generate_data.py but cannot execute it, help please',
                          'Can\'t choose beautiful fonts for my site, everything looks awful',
                          'Never tried this before',
                          'I\'m trying to do this but end up with ModuleNotFoundError',
                          'I\'m scared',
                          'And what sorting is better']
        question_tags = [['django', 'python', 'web'],
                         ['geography', 'traveling'],
                         ['cinema', 'bestsellers'],
                         ['python'],
                         ['site', 'UX'],
                         ['django', 'python'],
                         ['web', 'site', 'fonts'],
                         ['django', 'web'],
                         ['django', 'python'],
                         ['git'],
                         ['algorithms']]
        question_answers = [['Read tutorials', 'Ask friends'],
                            ['Prague'],
                            ['It\'s a fantastic film', 'The actor\'s play is good',
                             'You should see it', 'Everywhere I go'],
                            ['Syntactic sugar'],
                            ['It\'s two days that I\'ve been trying to find it but it seems quite useless',
                             'Sorry, guys, the button will be added soon, I\'m currently adding some questions '
                             'and answers to database'],
                            ['Try \'python manage.py generate_data\''],
                            ['Try to search on fonts.google.com, they offer popular pairings as well, it\'s '
                             'very useful', 'Montserrat is my favourite', 'I like Quicksand'],
                            ['Never wanted more', 'https://docs.djangoproject.com/en/2.2/intro/tutorial01/'],
                            ['Do not import in managers, use self.object (for example)'],
                            ['Use --soft but do a pair of backups just in case', '--soft is a default parameter'],
                            ['For example https://neerc.ifmo.ru/wiki/index.php']]

        for i in range(len(question_titles)):
            q = Question(author=Profile.objects.get(id=randint(1, Profile.objects.count())),
                         title=question_titles[i],
                         text=question_texts[i])
            q.save()
            for tag_name in question_tags[i]:
                q.tags.add(Tag.objects.get(name=tag_name))
            q.save()
            for text in question_answers[i]:
                ans = Answer(author=Profile.objects.get(id=randint(1, Profile.objects.count())),
                             question=q,
                             text=text)
                ans.save()