def test_page_2_without_next(self):
     """Test page=2, doesn't have next page."""
     request = self.rf.get('/questions?page=2')
     queryset = [{}, {}, {}]
     page = simple_paginate(request, queryset, per_page=2)
     eq_(2, page.number)
     assert page.has_previous()
     assert not page.has_next()
Example #2
0
 def test_page_2_without_next(self):
     """Test page=2, doesn't have next page."""
     request = self.rf.get('/questions?page=2')
     queryset = [{}, {}, {}]
     page = simple_paginate(request, queryset, per_page=2)
     eq_(2, page.number)
     assert page.has_previous()
     assert not page.has_next()
 def test_page_1_with_next(self):
     """Test page=1, has next page."""
     request = self.rf.get('/questions?page=1')
     queryset = [{}, {}, {}]
     page = simple_paginate(request, queryset, per_page=2)
     eq_(1, page.number)
     assert not page.has_previous()
     assert page.has_next()
Example #4
0
 def test_page_1_with_next(self):
     """Test page=1, has next page."""
     request = self.rf.get('/questions?page=1')
     queryset = [{}, {}, {}]
     page = simple_paginate(request, queryset, per_page=2)
     eq_(1, page.number)
     assert not page.has_previous()
     assert page.has_next()
Example #5
0
def questions(request, template):
    """View the questions."""

    filter_ = request.GET.get('filter')
    tagged = request.GET.get('tagged')
    tags = None
    sort_ = request.GET.get('sort', None)

    if sort_ == 'requested':
        order = '-num_votes_past_week'
    elif sort_ == 'created':
        order = '-created'
    else:
        order = '-updated'

    question_qs = Question.objects.select_related(
        'creator', 'last_answer', 'last_answer__creator')

    if not waffle.switch_is_active('hide-total-question-votes'):
        question_qs = question_qs.extra(
            {'_num_votes': 'SELECT COUNT(*) FROM questions_questionvote WHERE '
                           'questions_questionvote.question_id = '
                           'questions_question.id'})

    question_qs = question_qs.filter(creator__is_active=1)

    if filter_ == 'no-replies':
        question_qs = question_qs.filter(num_answers=0, is_locked=False)
    elif filter_ == 'replies':
        question_qs = question_qs.filter(num_answers__gt=0)
    elif filter_ == 'solved':
        question_qs = question_qs.exclude(solution=None)
    elif filter_ == 'unsolved':
        question_qs = question_qs.filter(solution=None)
    elif filter_ == 'my-contributions' and request.user.is_authenticated():
        criteria = Q(answers__creator=request.user) | Q(creator=request.user)
        question_qs = question_qs.filter(criteria).distinct()
    elif filter_ == 'recent-unanswered':
        # Only unanswered questions from the last 72 hours.
        start = datetime.now() - timedelta(hours=72)
        question_qs = question_qs.filter(
            num_answers=0, created__gt=start, is_locked=False)
    else:
        filter_ = None

    feed_urls = ((reverse('questions.feed'),
                  QuestionsFeed().title()),)

    if tagged:
        tag_slugs = tagged.split(',')
        tags = Tag.objects.filter(slug__in=tag_slugs)
        if tags:
            for t in tags:
                question_qs = question_qs.filter(tags__name__in=[t.name])
            if len(tags) == 1:
                feed_urls += ((reverse('questions.tagged_feed',
                                       args=[tags[0].slug]),
                               TaggedQuestionsFeed().title(tags[0])),)
        else:
            question_qs = Question.objects.get_empty_query_set()

    # Exclude questions over 90 days old without an answer.
    oldest_date = date.today() - timedelta(days=90)
    question_qs = question_qs.exclude(created__lt=oldest_date, num_answers=0)

    # Set the order.
    question_qs = question_qs.order_by(order)

    try:
        with statsd.timer('questions.view.paginate.%s' % filter_):
            questions_page = simple_paginate(
                request, question_qs, per_page=constants.QUESTIONS_PER_PAGE)
    except (PageNotAnInteger, EmptyPage):
        # If we aren't on page 1, redirect there.
        # TODO: Is 404 more appropriate?
        if request.GET.get('page', '1') != '1':
            url = build_paged_url(request)
            return HttpResponseRedirect(urlparams(url, page=1))

    # Recent answered stats
    recent_asked_count = Question.recent_asked_count()
    recent_unanswered_count = Question.recent_unanswered_count()
    if recent_asked_count:
        recent_answered_percent = int(
            (float(recent_asked_count - recent_unanswered_count) /
            recent_asked_count) * 100)
    else:
        recent_answered_percent = 0

    data = {'questions': questions_page,
            'feeds': feed_urls,
            'filter': filter_,
            'sort': sort_,
            'tags': tags,
            'tagged': tagged,
            'recent_asked_count': recent_asked_count,
            'recent_unanswered_count': recent_unanswered_count,
            'recent_answered_percent': recent_answered_percent}

    if (waffle.flag_is_active(request, 'karma') and
        waffle.switch_is_active('karma')):
        kmgr = KarmaManager()
        data.update(karma_top=kmgr.top_users('3m'))
        if request.user.is_authenticated():
            ranking = kmgr.ranking('3m', request.user)
            if ranking <= constants.HIGHEST_RANKING:
                data.update(karma_ranking=ranking)
    else:
        data.update(top_contributors=_get_top_contributors())

    with statsd.timer('questions.view.render'):
        return jingo.render(request, template, data)
 def test_page_isnt_an_int(self):
     """Test page=1, has next page."""
     request = self.rf.get('/questions?page=foo')
     queryset = [{}, {}]
     simple_paginate(request, queryset, per_page=2)
 def test_page_2_empty(self):
     """Test page=1, has next page."""
     request = self.rf.get('/questions?page=2')
     queryset = [{}, {}]
     simple_paginate(request, queryset, per_page=2)
 def test_no_explicit_page(self):
     """No 'page' query param implies page 1."""
     request = self.rf.get('/questions')
     queryset = [{}, {}]
     page = simple_paginate(request, queryset, per_page=2)
     eq_(1, page.number)
Example #9
0
 def test_page_isnt_an_int(self):
     """Test page=1, has next page."""
     request = self.rf.get('/questions?page=foo')
     queryset = [{}, {}]
     simple_paginate(request, queryset, per_page=2)
Example #10
0
 def test_page_2_empty(self):
     """Test page=1, has next page."""
     request = self.rf.get('/questions?page=2')
     queryset = [{}, {}]
     simple_paginate(request, queryset, per_page=2)
Example #11
0
 def test_no_explicit_page(self):
     """No 'page' query param implies page 1."""
     request = self.rf.get('/questions')
     queryset = [{}, {}]
     page = simple_paginate(request, queryset, per_page=2)
     eq_(1, page.number)
Example #12
0
def questions(request, template):
    """View the questions."""

    filter_ = request.GET.get("filter")
    tagged = request.GET.get("tagged")
    tags = None
    sort_ = request.GET.get("sort", None)
    product_slug = request.GET.get("product")

    if sort_ == "requested":
        order = ["-num_votes_past_week", "-_num_votes"]
    elif sort_ == "created":
        order = ["-created"]
    else:
        order = ["-updated"]

    if product_slug:
        product = get_object_or_404(Product, slug=product_slug)
    else:
        product = None

    question_qs = Question.objects.select_related("creator", "last_answer", "last_answer__creator")

    if not waffle.switch_is_active("hide-total-question-votes") or sort_ == "requested":
        question_qs = question_qs.extra(
            {
                "_num_votes": "SELECT COUNT(*) FROM questions_questionvote WHERE "
                "questions_questionvote.question_id = "
                "questions_question.id"
            }
        )

    question_qs = question_qs.filter(creator__is_active=1)

    if filter_ == "no-replies":
        question_qs = question_qs.filter(num_answers=0, is_locked=False)
    elif filter_ == "replies":
        question_qs = question_qs.filter(num_answers__gt=0)
    elif filter_ == "solved":
        question_qs = question_qs.exclude(solution=None)
    elif filter_ == "unsolved":
        question_qs = question_qs.filter(solution=None)
    elif filter_ == "my-contributions" and request.user.is_authenticated():
        criteria = Q(answers__creator=request.user) | Q(creator=request.user)
        question_qs = question_qs.filter(criteria).distinct()
    elif filter_ == "recent-unanswered":
        # Only unanswered questions from the last 72 hours.
        start = datetime.now() - timedelta(hours=72)
        question_qs = question_qs.filter(num_answers=0, created__gt=start, is_locked=False)
    else:
        filter_ = None

    feed_urls = ((reverse("questions.feed"), QuestionsFeed().title()),)

    if tagged:
        tag_slugs = tagged.split(",")
        tags = Tag.objects.filter(slug__in=tag_slugs)
        if tags:
            for t in tags:
                question_qs = question_qs.filter(tags__name__in=[t.name])
            if len(tags) == 1:
                feed_urls += (
                    (reverse("questions.tagged_feed", args=[tags[0].slug]), TaggedQuestionsFeed().title(tags[0])),
                )
        else:
            question_qs = Question.objects.get_empty_query_set()

    # Exclude questions over 90 days old without an answer.
    oldest_date = date.today() - timedelta(days=90)
    question_qs = question_qs.exclude(created__lt=oldest_date, num_answers=0)

    # Filter by product.
    if product:
        # This filter will match if any of the products on a question have the
        # correct id.
        question_qs = question_qs.filter(products__id__exact=product.id)

    # Set the order.
    question_qs = question_qs.order_by(*order)

    try:
        with statsd.timer("questions.view.paginate.%s" % filter_):
            questions_page = simple_paginate(request, question_qs, per_page=constants.QUESTIONS_PER_PAGE)
    except (PageNotAnInteger, EmptyPage):
        # If we aren't on page 1, redirect there.
        # TODO: Is 404 more appropriate?
        if request.GET.get("page", "1") != "1":
            url = build_paged_url(request)
            return HttpResponseRedirect(urlparams(url, page=1))

    # Recent answered stats
    recent_asked_count = Question.recent_asked_count()
    recent_unanswered_count = Question.recent_unanswered_count()
    if recent_asked_count:
        recent_answered_percent = int((float(recent_asked_count - recent_unanswered_count) / recent_asked_count) * 100)
    else:
        recent_answered_percent = 0

    # List of products to fill the selector.
    product_list = Product.objects.filter(visible=True)

    data = {
        "questions": questions_page,
        "feeds": feed_urls,
        "filter": filter_,
        "sort": sort_,
        "tags": tags,
        "tagged": tagged,
        "recent_asked_count": recent_asked_count,
        "recent_unanswered_count": recent_unanswered_count,
        "recent_answered_percent": recent_answered_percent,
        "product_list": product_list,
        "product": product,
    }

    if waffle.flag_is_active(request, "karma") and waffle.switch_is_active("karma"):
        kmgr = KarmaManager()
        data.update(karma_top=kmgr.top_users("3m"))
        if request.user.is_authenticated():
            ranking = kmgr.ranking("3m", request.user)
            if ranking <= constants.HIGHEST_RANKING:
                data.update(karma_ranking=ranking)
    else:
        data.update(top_contributors=_get_top_contributors())

    with statsd.timer("questions.view.render"):
        return jingo.render(request, template, data)
Example #13
0
def questions(request):
    """View the questions."""

    filter_ = request.GET.get('filter')
    tagged = request.GET.get('tagged')
    tags = None
    sort_ = request.GET.get('sort', None)

    if sort_ == 'requested':
        order = '-num_votes_past_week'
    elif sort_ == 'created':
        order = '-created'
    else:
        order = '-updated'

    question_qs = Question.objects.select_related('creator', 'last_answer',
                                                  'last_answer__creator')

    if not waffle.switch_is_active('hide-total-question-votes'):
        question_qs = question_qs.extra({
            '_num_votes':
            'SELECT COUNT(*) FROM questions_questionvote WHERE '
            'questions_questionvote.question_id = '
            'questions_question.id'
        })

    question_qs = question_qs.filter(creator__is_active=1)

    if filter_ == 'no-replies':
        question_qs = question_qs.filter(num_answers=0, is_locked=False)
    elif filter_ == 'replies':
        question_qs = question_qs.filter(num_answers__gt=0)
    elif filter_ == 'solved':
        question_qs = question_qs.exclude(solution=None)
    elif filter_ == 'unsolved':
        question_qs = question_qs.filter(solution=None)
    elif filter_ == 'my-contributions' and request.user.is_authenticated():
        criteria = Q(answers__creator=request.user) | Q(creator=request.user)
        question_qs = question_qs.filter(criteria).distinct()
    elif filter_ == 'recent-unanswered':
        # Only unanswered questions from the last 72 hours.
        start = datetime.now() - timedelta(hours=72)
        question_qs = question_qs.filter(num_answers=0,
                                         created__gt=start,
                                         is_locked=False)
    else:
        filter_ = None

    feed_urls = ((reverse('questions.feed'), QuestionsFeed().title()), )

    if tagged:
        tag_slugs = tagged.split(',')
        tags = Tag.objects.filter(slug__in=tag_slugs)
        if tags:
            for t in tags:
                question_qs = question_qs.filter(tags__name__in=[t.name])
            if len(tags) == 1:
                feed_urls += ((reverse('questions.tagged_feed',
                                       args=[tags[0].slug]),
                               TaggedQuestionsFeed().title(tags[0])), )
        else:
            question_qs = Question.objects.get_empty_query_set()

    # Exclude questions over 90 days old without an answer.
    oldest_date = date.today() - timedelta(days=90)
    question_qs = question_qs.exclude(created__lt=oldest_date, num_answers=0)

    # Set the order.
    question_qs = question_qs.order_by(order)

    try:
        with statsd.timer('questions.view.paginate.%s' % filter_):
            questions_page = simple_paginate(
                request, question_qs, per_page=constants.QUESTIONS_PER_PAGE)
    except (PageNotAnInteger, EmptyPage):
        # If we aren't on page 1, redirect there.
        # TODO: Is 404 more appropriate?
        if request.GET.get('page', '1') != '1':
            url = build_paged_url(request)
            return HttpResponseRedirect(urlparams(url, page=1))

    # Recent answered stats
    recent_asked_count = Question.recent_asked_count()
    recent_unanswered_count = Question.recent_unanswered_count()
    if recent_asked_count:
        recent_answered_percent = int(
            (float(recent_asked_count - recent_unanswered_count) /
             recent_asked_count) * 100)
    else:
        recent_answered_percent = 0

    data = {
        'questions': questions_page,
        'feeds': feed_urls,
        'filter': filter_,
        'sort': sort_,
        'tags': tags,
        'tagged': tagged,
        'recent_asked_count': recent_asked_count,
        'recent_unanswered_count': recent_unanswered_count,
        'recent_answered_percent': recent_answered_percent
    }

    if (waffle.flag_is_active(request, 'karma')
            and waffle.switch_is_active('karma')):
        kmgr = KarmaManager()
        data.update(karma_top=kmgr.top_users())
        if request.user.is_authenticated():
            ranking = kmgr.ranking(request.user)
            if ranking <= constants.HIGHEST_RANKING:
                data.update(karma_ranking=ranking)
    else:
        data.update(top_contributors=_get_top_contributors())

    with statsd.timer('questions.view.render'):
        return jingo.render(request, 'questions/questions.html', data)