Beispiel #1
0
def questions(request, **kwargs):
    """
    List of Questions, Tagged questions, and Unanswered questions.
    matching search query or user selection
    """
    # before = datetime.datetime.now()
    if request.method != "GET":
        return HttpResponseNotAllowed(["GET"])

    search_state = SearchState(user_logged_in=request.user.is_authenticated(), **kwargs)
    page_size = int(askbot_settings.DEFAULT_QUESTIONS_PAGE_SIZE)

    qs, meta_data = models.Thread.objects.run_advanced_search(request_user=request.user, search_state=search_state)
    if meta_data["non_existing_tags"]:
        search_state = search_state.remove_tags(meta_data["non_existing_tags"])

    paginator = Paginator(qs, page_size)
    if paginator.num_pages < search_state.page:
        search_state.page = 1
    page = paginator.page(search_state.page)
    page.object_list = list(page.object_list)  # evaluate the queryset

    # INFO: Because for the time being we need question posts and thread authors
    #       down the pipeline, we have to precache them in thread objects
    models.Thread.objects.precache_view_data_hack(threads=page.object_list)

    related_tags = Tag.objects.get_related_to_search(
        threads=page.object_list, ignored_tag_names=meta_data.get("ignored_tag_names", [])
    )
    tag_list_type = askbot_settings.TAG_LIST_FORMAT
    if tag_list_type == "cloud":  # force cloud to sort by name
        related_tags = sorted(related_tags, key=operator.attrgetter("name"))

    contributors = list(
        models.Thread.objects.get_thread_contributors(thread_list=page.object_list).only("id", "username", "gravatar")
    )

    paginator_context = {
        "is_paginated": (paginator.count > page_size),
        "pages": paginator.num_pages,
        "page": search_state.page,
        "has_previous": page.has_previous(),
        "has_next": page.has_next(),
        "previous": page.previous_page_number(),
        "next": page.next_page_number(),
        "base_url": search_state.query_string(),
        "page_size": page_size,
    }

    # We need to pass the rss feed url based
    # on the search state to the template.
    # We use QueryDict to get a querystring
    # from dicts and arrays. Much cleaner
    # than parsing and string formating.
    rss_query_dict = QueryDict("").copy()
    if search_state.query:
        # We have search string in session - pass it to
        # the QueryDict
        rss_query_dict.update({"q": search_state.query})
    if search_state.tags:
        # We have tags in session - pass it to the
        # QueryDict but as a list - we want tags+
        rss_query_dict.setlist("tags", search_state.tags)
    context_feed_url = "/%sfeeds/rss/?%s" % (
        settings.ASKBOT_URL,
        rss_query_dict.urlencode(),
    )  # Format the url with the QueryDict

    reset_method_count = len(filter(None, [search_state.query, search_state.tags, meta_data.get("author_name", None)]))

    if request.is_ajax():
        q_count = paginator.count

        question_counter = ungettext("%(q_num)s question", "%(q_num)s questions", q_count)
        question_counter = question_counter % {"q_num": humanize.intcomma(q_count)}

        if q_count > page_size:
            paginator_tpl = get_template("main_page/paginator.html", request)
            paginator_html = paginator_tpl.render(
                Context(
                    {
                        "context": functions.setup_paginator(paginator_context),
                        "questions_count": q_count,
                        "page_size": page_size,
                        "search_state": search_state,
                    }
                )
            )
        else:
            paginator_html = ""

        questions_tpl = get_template("main_page/questions_loop.html", request)
        questions_html = questions_tpl.render(
            Context(
                {
                    "threads": page,
                    "search_state": search_state,
                    "reset_method_count": reset_method_count,
                    "request": request,
                }
            )
        )

        ajax_data = {
            "query_data": {
                "tags": search_state.tags,
                "sort_order": search_state.sort,
                "ask_query_string": search_state.ask_query_string(),
            },
            "paginator": paginator_html,
            "question_counter": question_counter,
            "faces": [],  # [extra_tags.gravatar(contributor, 48) for contributor in contributors],
            "feed_url": context_feed_url,
            "query_string": search_state.query_string(),
            "page_size": page_size,
            "questions": questions_html.replace("\n", ""),
            "non_existing_tags": meta_data["non_existing_tags"],
        }
        ajax_data["related_tags"] = [
            {"name": escape(tag.name), "used_count": humanize.intcomma(tag.local_used_count)} for tag in related_tags
        ]

        return HttpResponse(simplejson.dumps(ajax_data), mimetype="application/json")

    else:  # non-AJAX branch

        template_data = {
            "active_tab": "questions",
            "author_name": meta_data.get("author_name", None),
            "contributors": contributors,
            "context": paginator_context,
            "is_unanswered": False,  # remove this from template
            "interesting_tag_names": meta_data.get("interesting_tag_names", None),
            "ignored_tag_names": meta_data.get("ignored_tag_names", None),
            "subscribed_tag_names": meta_data.get("subscribed_tag_names", None),
            "language_code": translation.get_language(),
            "name_of_anonymous_user": models.get_name_of_anonymous_user(),
            "page_class": "main-page",
            "page_size": page_size,
            "query": search_state.query,
            "threads": page,
            "questions_count": paginator.count,
            "reset_method_count": reset_method_count,
            "scope": search_state.scope,
            "show_sort_by_relevance": conf.should_show_sort_by_relevance(),
            "search_tags": search_state.tags,
            "sort": search_state.sort,
            "tab_id": search_state.sort,
            "tags": related_tags,
            "tag_list_type": tag_list_type,
            "font_size": extra_tags.get_tag_font_size(related_tags),
            "display_tag_filter_strategy_choices": conf.get_tag_display_filter_strategy_choices(),
            "email_tag_filter_strategy_choices": const.TAG_EMAIL_FILTER_STRATEGY_CHOICES,
            "update_avatar_data": schedules.should_update_avatar_data(request),
            "query_string": search_state.query_string(),
            "search_state": search_state,
            "feed_url": context_feed_url,
        }

        return render_into_skin("main_page.html", template_data, request)
Beispiel #2
0
def questions(request, **kwargs):
    """
    List of Questions, Tagged questions, and Unanswered questions.
    matching search query or user selection
    """
    #before = datetime.datetime.now()
    if request.method != 'GET':
        return HttpResponseNotAllowed(['GET'])

    search_state = SearchState(
                    user_logged_in=request.user.is_authenticated(),
                    **kwargs
                )
    page_size = int(askbot_settings.DEFAULT_QUESTIONS_PAGE_SIZE)

    qs, meta_data = models.Thread.objects.run_advanced_search(
                        request_user=request.user, search_state=search_state
                    )
    
    
    current_lang = request.session['django_language']
    langs = settings.ASKBOT_LANG_TAGS.copy()
    if current_lang in langs:
        langs.pop(current_lang)

    if current_lang == 'en':
        qs = qs.exclude(tags__name__in=langs)
    else:
        qs = qs.filter(tags__name=current_lang)
        

    if meta_data['non_existing_tags']:
        search_state = search_state.remove_tags(meta_data['non_existing_tags'])

    paginator = Paginator(qs, page_size)
    if paginator.num_pages < search_state.page:
        search_state.page = 1
    page = paginator.page(search_state.page)
    page.object_list = list(page.object_list) # evaluate the queryset

    # INFO: Because for the time being we need question posts and thread authors
    #       down the pipeline, we have to precache them in thread objects
    models.Thread.objects.precache_view_data_hack(threads=page.object_list)

    related_tags = Tag.objects.get_related_to_search(
                        threads=page.object_list,
                        ignored_tag_names=meta_data.get('ignored_tag_names',[])
                    )
    tag_list_type = askbot_settings.TAG_LIST_FORMAT
    if tag_list_type == 'cloud': #force cloud to sort by name
        related_tags = sorted(related_tags, key = operator.attrgetter('name'))

    contributors = list(
        models.Thread.objects.get_thread_contributors(
                                        thread_list=page.object_list
                                    ).only('id', 'username', 'gravatar')
                        )

    paginator_context = {
        'is_paginated' : (paginator.count > page_size),

        'pages': paginator.num_pages,
        'page': search_state.page,
        'has_previous': page.has_previous(),
        'has_next': page.has_next(),
        'previous': page.previous_page_number(),
        'next': page.next_page_number(),

        'base_url' : search_state.query_string(),
        'page_size' : page_size,
    }

    # We need to pass the rss feed url based
    # on the search state to the template.
    # We use QueryDict to get a querystring
    # from dicts and arrays. Much cleaner
    # than parsing and string formating.
    rss_query_dict = QueryDict("").copy()
    if search_state.query:
        # We have search string in session - pass it to
        # the QueryDict
        rss_query_dict.update({"q": search_state.query})
    if search_state.tags:
        # We have tags in session - pass it to the
        # QueryDict but as a list - we want tags+
        rss_query_dict.setlist("tags", search_state.tags)
    context_feed_url = '/%sfeeds/rss/?%s' % (settings.ASKBOT_URL, rss_query_dict.urlencode()) # Format the url with the QueryDict

    reset_method_count = len(filter(None, [search_state.query, search_state.tags, meta_data.get('author_name', None)]))

    if request.is_ajax():
        q_count = paginator.count

        question_counter = ungettext('%(q_num)s question', '%(q_num)s questions', q_count)
        question_counter = question_counter % {'q_num': humanize.intcomma(q_count),}

        if q_count > page_size:
            paginator_tpl = get_template('main_page/paginator.html')
            paginator_html = paginator_tpl.render(
                RequestContext(
                    request, {
                        'context': functions.setup_paginator(paginator_context),
                        'questions_count': q_count,
                        'page_size' : page_size,
                        'search_state': search_state,
                    }
                )
            )
        else:
            paginator_html = ''

        questions_tpl = get_template('main_page/questions_loop.html')
        questions_html = questions_tpl.render(
            RequestContext(
                request, {
                    'threads': page,
                    'search_state': search_state,
                    'reset_method_count': reset_method_count,
                    'request': request
                }
            )
        )

        ajax_data = {
            'query_data': {
                'tags': search_state.tags,
                'sort_order': search_state.sort,
                'ask_query_string': search_state.ask_query_string(),
            },
            'paginator': paginator_html,
            'question_counter': question_counter,
            'faces': [],#[extra_tags.gravatar(contributor, 48) for contributor in contributors],
            'feed_url': context_feed_url,
            'query_string': search_state.query_string(),
            'page_size' : page_size,
            'questions': questions_html.replace('\n',''),
            'non_existing_tags': meta_data['non_existing_tags']
        }
        ajax_data['related_tags'] = [{
            'name': escape(tag.name),
            'used_count': humanize.intcomma(tag.local_used_count)
        } for tag in related_tags]

        return HttpResponse(simplejson.dumps(ajax_data), mimetype = 'application/json')

    else: # non-AJAX branch

        template_data = {
            'active_tab': 'questions',
            'author_name' : meta_data.get('author_name',None),
            'contributors' : contributors,
            'context' : paginator_context,
            'is_unanswered' : False,#remove this from template
            'interesting_tag_names': meta_data.get('interesting_tag_names', None),
            'ignored_tag_names': meta_data.get('ignored_tag_names', None),
            'subscribed_tag_names': meta_data.get('subscribed_tag_names', None),
            'language_code': translation.get_language(),
            'name_of_anonymous_user' : models.get_name_of_anonymous_user(),
            'page_class': 'main-page',
            'page_size': page_size,
            'query': search_state.query,
            'threads' : page,
            'questions_count' : paginator.count,
            'reset_method_count': reset_method_count,
            'scope': search_state.scope,
            'show_sort_by_relevance': conf.should_show_sort_by_relevance(),
            'search_tags' : search_state.tags,
            'sort': search_state.sort,
            'tab_id' : search_state.sort,
            'tags' : related_tags,
            'tag_list_type' : tag_list_type,
            'font_size' : extra_tags.get_tag_font_size(related_tags),
            'display_tag_filter_strategy_choices': conf.get_tag_display_filter_strategy_choices(),
            'email_tag_filter_strategy_choices': const.TAG_EMAIL_FILTER_STRATEGY_CHOICES,
            'update_avatar_data': schedules.should_update_avatar_data(request),
            'query_string': search_state.query_string(),
            'search_state': search_state,
            'feed_url': context_feed_url,
            'lang_tags': settings.ASKBOT_LANG_TAGS,
        }

        return render(request, 'main_page.html', template_data)
Beispiel #3
0
def questions(request, **kwargs):
    """
    List of Questions, Tagged questions, and Unanswered questions.
    matching search query or user selection
    """
    if request.method != 'GET':
        return HttpResponseNotAllowed(['GET'])

    search_state = SearchState(user_logged_in=request.user.is_authenticated(),
                               **kwargs)
    page_size = int(askbot_settings.DEFAULT_QUESTIONS_PAGE_SIZE)

    qs, meta_data = models.Thread.objects.run_advanced_search(
        request_user=request.user, search_state=search_state)

    if meta_data['non_existing_tags']:
        search_state = search_state.remove_tags(meta_data['non_existing_tags'])

    paginator = Paginator(qs, page_size)
    if paginator.num_pages < search_state.page:
        search_state.page = 1
    page = paginator.page(search_state.page)

    page.object_list = list(page.object_list)  # evaluate queryset

    # INFO: Because for the time being we need question posts and thread authors
    #       down the pipeline, we have to precache them in thread objects
    models.Thread.objects.precache_view_data_hack(threads=page.object_list)

    related_tags = Tag.objects.get_related_to_search(
        threads=page.object_list,
        ignored_tag_names=meta_data.get('ignored_tag_names', []))
    tag_list_type = askbot_settings.TAG_LIST_FORMAT
    if tag_list_type == 'cloud':  #force cloud to sort by name
        related_tags = sorted(related_tags, key=operator.attrgetter('name'))

    contributors = list(
        models.Thread.objects.get_thread_contributors(
            thread_list=page.object_list).only('id', 'username', 'gravatar'))

    paginator_context = {
        'is_paginated': (paginator.count > page_size),
        'pages': paginator.num_pages,
        'page': search_state.page,
        'has_previous': page.has_previous(),
        'has_next': page.has_next(),
        'previous': page.previous_page_number(),
        'next': page.next_page_number(),
        'base_url': search_state.query_string(),
        'page_size': page_size,
    }

    # We need to pass the rss feed url based
    # on the search state to the template.
    # We use QueryDict to get a querystring
    # from dicts and arrays. Much cleaner
    # than parsing and string formating.
    rss_query_dict = QueryDict("").copy()
    if search_state.query:
        # We have search string in session - pass it to
        # the QueryDict
        rss_query_dict.update({"q": search_state.query})
    if search_state.tags:
        # We have tags in session - pass it to the
        # QueryDict but as a list - we want tags+
        rss_query_dict.setlist("tags", search_state.tags)
    context_feed_url = '/feeds/rss/?%s' % rss_query_dict.urlencode(
    )  # Format the url with the QueryDict

    reset_method_count = len(
        filter(None, [
            search_state.query, search_state.tags,
            meta_data.get('author_name', None)
        ]))

    if request.is_ajax():
        q_count = paginator.count

        question_counter = ungettext('%(q_num)s question',
                                     '%(q_num)s questions', q_count)
        question_counter = question_counter % {
            'q_num': humanize.intcomma(q_count),
        }

        if q_count > page_size:
            paginator_tpl = get_template('main_page/paginator.html', request)
            paginator_html = paginator_tpl.render(
                Context({
                    'context': functions.setup_paginator(paginator_context),
                    'questions_count': q_count,
                    'page_size': page_size,
                    'search_state': search_state,
                }))
        else:
            paginator_html = ''

        questions_tpl = get_template('main_page/questions_loop.html', request)
        questions_html = questions_tpl.render(
            Context({
                'threads': page,
                'search_state': search_state,
                'reset_method_count': reset_method_count,
            }))

        ajax_data = {
            'query_data': {
                'tags': search_state.tags,
                'sort_order': search_state.sort,
                'ask_query_string': search_state.ask_query_string(),
            },
            'paginator':
            paginator_html,
            'question_counter':
            question_counter,
            'faces': [
                extra_tags.gravatar(contributor, 48)
                for contributor in contributors
            ],
            'feed_url':
            context_feed_url,
            'query_string':
            search_state.query_string(),
            'page_size':
            page_size,
            'questions':
            questions_html.replace('\n', ''),
            'non_existing_tags':
            meta_data['non_existing_tags']
        }
        ajax_data['related_tags'] = [{
            'name':
            tag.name,
            'used_count':
            humanize.intcomma(tag.local_used_count)
        } for tag in related_tags]

        return HttpResponse(simplejson.dumps(ajax_data),
                            mimetype='application/json')

    else:  # non-AJAX branch

        template_data = {
            'active_tab': 'questions',
            'author_name': meta_data.get('author_name', None),
            'contributors': contributors,
            'context': paginator_context,
            'is_unanswered': False,  #remove this from template
            'interesting_tag_names': meta_data.get('interesting_tag_names',
                                                   None),
            'ignored_tag_names': meta_data.get('ignored_tag_names', None),
            'subscribed_tag_names': meta_data.get('subscribed_tag_names',
                                                  None),
            'language_code': translation.get_language(),
            'name_of_anonymous_user': models.get_name_of_anonymous_user(),
            'page_class': 'main-page',
            'page_size': page_size,
            'query': search_state.query,
            'threads': page,
            'questions_count': paginator.count,
            'reset_method_count': reset_method_count,
            'scope': search_state.scope,
            'show_sort_by_relevance':
            askbot.conf.should_show_sort_by_relevance(),
            'search_tags': search_state.tags,
            'sort': search_state.sort,
            'tab_id': search_state.sort,
            'tags': related_tags,
            'tag_list_type': tag_list_type,
            'font_size': extra_tags.get_tag_font_size(related_tags),
            'display_tag_filter_strategy_choices':
            const.TAG_DISPLAY_FILTER_STRATEGY_CHOICES,
            'email_tag_filter_strategy_choices':
            const.TAG_EMAIL_FILTER_STRATEGY_CHOICES,
            'update_avatar_data': schedules.should_update_avatar_data(request),
            'query_string': search_state.query_string(),
            'search_state': search_state,
            'feed_url': context_feed_url,
        }

        return render_into_skin('main_page.html', template_data, request)
Beispiel #4
0
def questions(request, **kwargs):
    """
    List of Questions, Tagged questions, and Unanswered questions.
    matching search query or user selection
    """
    #before = datetime.datetime.now()
    if request.method != 'GET':
        return HttpResponseNotAllowed(['GET'])

    search_state = SearchState(
                    user_logged_in=request.user.is_authenticated(),
                    **kwargs
                )
    page_size = int(askbot_settings.DEFAULT_QUESTIONS_PAGE_SIZE)

    qs, meta_data = models.Thread.objects.run_advanced_search(
                        request_user=request.user, search_state=search_state
                    )
    if meta_data['non_existing_tags']:
        search_state = search_state.remove_tags(meta_data['non_existing_tags'])

    paginator = Paginator(qs, page_size)
    if paginator.num_pages < search_state.page:
        search_state.page = 1
    page = paginator.page(search_state.page)
    page.object_list = list(page.object_list) # evaluate the queryset

    # INFO: Because for the time being we need question posts and thread authors
    #       down the pipeline, we have to precache them in thread objects
    models.Thread.objects.precache_view_data_hack(threads=page.object_list)

    related_tags = Tag.objects.get_related_to_search(
                        threads=page.object_list,
                        ignored_tag_names=meta_data.get('ignored_tag_names',[])
                    )
    tag_list_type = askbot_settings.TAG_LIST_FORMAT
    if tag_list_type == 'cloud': #force cloud to sort by name
        related_tags = sorted(related_tags, key = operator.attrgetter('name'))

    contributors = list(
        models.Thread.objects.get_thread_contributors(
                                        thread_list=page.object_list
                                    ).only('id', 'username', 'gravatar')
                        )

    paginator_context = {
        'is_paginated' : (paginator.count > page_size),
        'pages': paginator.num_pages,
        'current_page_number': search_state.page,
        'page_object': page,
        'base_url' : search_state.query_string(),
        'page_size' : page_size,
    }

    # We need to pass the rss feed url based
    # on the search state to the template.
    # We use QueryDict to get a querystring
    # from dicts and arrays. Much cleaner
    # than parsing and string formating.
    rss_query_dict = QueryDict("").copy()
    if search_state.query:
        # We have search string in session - pass it to
        # the QueryDict
        rss_query_dict.update({"q": search_state.query})
    if search_state.tags:
        # We have tags in session - pass it to the
        # QueryDict but as a list - we want tags+
        rss_query_dict.setlist("tags", search_state.tags)
    context_feed_url = '/%sfeeds/rss/?%s' % (
                            django_settings.ASKBOT_URL,
                            rss_query_dict.urlencode()
                        ) # Format the url with the QueryDict

    reset_method_count = len(filter(None, [search_state.query, search_state.tags, meta_data.get('author_name', None)]))

    if request.is_ajax():
        q_count = paginator.count

        question_counter = ungettext('%(q_num)s question', '%(q_num)s questions', q_count)
        question_counter = question_counter % {'q_num': humanize.intcomma(q_count),}

        if q_count > page_size:
            paginator_tpl = get_template('main_page/paginator.html')
            paginator_html = paginator_tpl.render(
                RequestContext(
                    request, {
                        'context': functions.setup_paginator(paginator_context),
                        'questions_count': q_count,
                        'page_size' : page_size,
                        'search_state': search_state,
                    }
                )
            )
        else:
            paginator_html = ''

        questions_tpl = get_template('main_page/questions_loop.html')
        questions_html = questions_tpl.render(
            RequestContext(
                request, {
                    'threads': page,
                    'search_state': search_state,
                    'reset_method_count': reset_method_count,
                    'request': request
                }
            )
        )

        ajax_data = {
            'query_data': {
                'tags': search_state.tags,
                'sort_order': search_state.sort,
                'ask_query_string': search_state.ask_query_string(),
            },
            'paginator': paginator_html,
            'question_counter': question_counter,
            'faces': [],#[extra_tags.gravatar(contributor, 48) for contributor in contributors],
            'feed_url': context_feed_url,
            'query_string': search_state.query_string(),
            'page_size' : page_size,
            'questions': questions_html.replace('\n',''),
            'non_existing_tags': meta_data['non_existing_tags']
        }
        ajax_data['related_tags'] = [{
            'name': escape(tag.name),
            'used_count': humanize.intcomma(tag.local_used_count)
        } for tag in related_tags]

        return HttpResponse(simplejson.dumps(ajax_data), mimetype = 'application/json')

    else: # non-AJAX branch

        template_data = {
            'active_tab': 'questions',
            'author_name' : meta_data.get('author_name',None),
            'contributors' : contributors,
            'context' : paginator_context,
            'is_unanswered' : False,#remove this from template
            'interesting_tag_names': meta_data.get('interesting_tag_names', None),
            'ignored_tag_names': meta_data.get('ignored_tag_names', None),
            'subscribed_tag_names': meta_data.get('subscribed_tag_names', None),
            'language_code': translation.get_language(),
            'name_of_anonymous_user' : models.get_name_of_anonymous_user(),
            'page_class': 'main-page',
            'page_size': page_size,
            'query': search_state.query,
            'threads' : page,
            'questions_count' : paginator.count,
            'reset_method_count': reset_method_count,
            'scope': search_state.scope,
            'show_sort_by_relevance': conf.should_show_sort_by_relevance(),
            'search_tags' : search_state.tags,
            'sort': search_state.sort,
            'tab_id' : search_state.sort,
            'tags' : related_tags,
            'tag_list_type' : tag_list_type,
            'font_size' : extra_tags.get_tag_font_size(related_tags),
            'display_tag_filter_strategy_choices': conf.get_tag_display_filter_strategy_choices(),
            'email_tag_filter_strategy_choices': conf.get_tag_email_filter_strategy_choices(),
            'update_avatar_data': schedules.should_update_avatar_data(request),
            'query_string': search_state.query_string(),
            'search_state': search_state,
            'feed_url': context_feed_url,
        }

        extra_context = context.get_extra(
                                    'ASKBOT_QUESTIONS_PAGE_EXTRA_CONTEXT',
                                    request,
                                    template_data
                                )
        template_data.update(extra_context)

        #and one more thing:) give admin user heads up about
        #setting the domain name if they have not done that yet
        #todo: move this out to a separate middleware
        if request.user.is_authenticated() and request.user.is_administrator():
            if domain_is_bad():
                url = reverse(
                    'group_settings',
                    kwargs = {'group': 'QA_SITE_SETTINGS'}
                )
                url = url + '#id_QA_SITE_SETTINGS__APP_URL'
                msg = _(
                    'Please go to '
                    '<a href="%s">"settings->URLs, keywords and greetings"</a> '
                    'and set the base url for your site to function properly'
                ) % url
                request.user.message_set.create(message=msg)

        return render(request, 'main_page.html', template_data)
Beispiel #5
0
def questions(request, scope=const.DEFAULT_POST_SCOPE, sort=const.DEFAULT_POST_SORT_METHOD, query=None, \
        search=None, tags=None, author=None, page=None, reset_tags=None, \
        reset_author=None, reset_query=None, start_over=True, \
        remove_tag=None, page_size=None):
    """
    List of Questions, Tagged questions, and Unanswered questions.
    matching search query or user selection
    """
    #make parameters dictionary
    params_dict = {
        'scope': scope,
        'sort': sort,
    }
    if query:
        params_dict['query'] = ' '.join(query.split('+'))
    if search:
        params_dict['search'] = search
    if tags:
        params_dict['tags'] = ' '.join(tags.split('+'))
    if author:
        params_dict['author'] = author
    if page:
        params_dict['page'] = page
    if reset_tags:
        params_dict['reset_tags'] = reset_tags
    if reset_author:
        params_dict['reset_author'] = reset_author
    if reset_query:
        params_dict['reset_query'] = reset_query
    if start_over:
        params_dict['start_over'] = start_over
    if remove_tag:
        params_dict['remove_tag'] = remove_tag.decode("utf8")
    if page_size:
        params_dict['page_size'] = page_size
    
    #before = datetime.datetime.now()
    #don't allow to post to this view
    if request.method == 'POST':
        raise Http404
    #update search state
    #form = AdvancedSearchForm(request.GET)
    form = AdvancedSearchForm(params_dict)
    if form.is_valid():
        user_input = form.cleaned_data
    else:
        user_input = None
    search_state = request.session.get('search_state', SearchState())
    view_log = request.session['view_log']
    search_state.update(user_input, view_log, request.user)
    request.session['search_state'] = search_state
    request.session.modified = True

    #force reset for debugging
    #search_state.reset()
    #request.session.modified = True

    #todo: have this call implemented for sphinx, mysql and pgsql
    (qs, meta_data, related_tags) = models.Question.objects.run_advanced_search(
                                            request_user = request.user,
                                            search_state = search_state,
                                        )

    tag_list_type = askbot_settings.TAG_LIST_FORMAT

    #force cloud to sort by name
    if tag_list_type == 'cloud':
        related_tags = sorted(related_tags, key = operator.attrgetter('name'))

    font_size = extra_tags.get_tag_font_size(related_tags)

    paginator = Paginator(qs, search_state.page_size)

    if paginator.num_pages < search_state.page:
        search_state.page = 1

    page = paginator.page(search_state.page)

    contributors = models.Question.objects.get_question_and_answer_contributors(page.object_list)

    paginator_context = {
        'is_paginated' : (paginator.count > search_state.page_size),
        'pages': paginator.num_pages,
        'page': search_state.page,
        'has_previous': page.has_previous(),
        'has_next': page.has_next(),
        'previous': page.previous_page_number(),
        'next': page.next_page_number(),
        'base_url' : search_state.query_string(),#todo in T sort=>sort_method
        'page_size' : search_state.page_size,#todo in T pagesize -> page_size
        'parameters': search_state.make_parameters(),
    }

    # We need to pass the rss feed url based
    # on the search state to the template.
    # We use QueryDict to get a querystring
    # from dicts and arrays. Much cleaner
    # than parsing and string formating.
    rss_query_dict = QueryDict("").copy()
    if search_state.query:
        # We have search string in session - pass it to
        # the QueryDict
        rss_query_dict.update({"q": search_state.query})
    if search_state.tags:
        # We have tags in session - pass it to the
        # QueryDict but as a list - we want tags+
        rss_query_dict.setlist("tags", search_state.tags)
    
    # Format the url with the QueryDict
    context_feed_url = '/feeds/rss/?%s' % rss_query_dict.urlencode()

    reset_method_count = 0
    if search_state.query:
        reset_method_count += 1
    if search_state.tags:
        reset_method_count += 1
    if meta_data.get('author_name',None):
        reset_method_count += 1

    if request.is_ajax():

        q_count = paginator.count
        if search_state.tags:
            question_counter = ungettext(
                                    '%(q_num)s question, tagged',
                                    '%(q_num)s questions, tagged',
                                    q_count
                                ) % {
                                    'q_num': humanize.intcomma(q_count),
                                }
        else:
            question_counter = ungettext(
                                    '%(q_num)s question',
                                    '%(q_num)s questions',
                                    q_count
                                ) % {
                                    'q_num': humanize.intcomma(q_count),
                                }

        if q_count > search_state.page_size:
            paginator_tpl = get_template('main_page/paginator.html', request)
            #todo: remove this patch on context after all templates are moved to jinja
            #paginator_context['base_url'] = request.path + '?sort=%s&' % search_state.sort
            data = {
                'context': extra_tags.cnprog_paginator(paginator_context),
                'questions_count': q_count,
                'page_size' : search_state.page_size,
            }
            paginator_html = paginator_tpl.render(Context(data))
        else:
            paginator_html = ''
        search_tags = list()
        if search_state.tags:
            search_tags = list(search_state.tags)
        query_data = {
            'tags': search_tags,
            'sort_order': search_state.sort
        }
        ajax_data = {
            #current page is 1 by default now
            #because ajax is only called by update in the search button
            'query_data': query_data,
            'paginator': paginator_html,
            'question_counter': question_counter,
            'questions': list(),
            'related_tags': list(),
            'faces': list(),
            'feed_url': context_feed_url,
            'query_string': search_state.query_string(),
            'parameters': search_state.make_parameters(),
            'page_size' : search_state.page_size,
        }

        badge_levels = dict(const.BADGE_TYPE_CHOICES)
        def pluralize_badge_count(count, level):
            return ungettext(
                '%(badge_count)d %(badge_level)s badge',
                '%(badge_count)d %(badge_level)s badges',
                count
            ) % {
                'badge_count': count,
                'badge_level': badge_levels[level]
            }

        gold_badge_css_class = const.BADGE_CSS_CLASSES[const.GOLD_BADGE],
        silver_badge_css_class = const.BADGE_CSS_CLASSES[const.SILVER_BADGE],
        bronze_badge_css_class = const.BADGE_CSS_CLASSES[const.BRONZE_BADGE],

        for tag in related_tags:
            tag_data = {
                'name': tag.name,
                'used_count': humanize.intcomma(tag.local_used_count)
            }
            ajax_data['related_tags'].append(tag_data)

        for contributor in contributors:
            ajax_data['faces'].append(extra_tags.gravatar(contributor, 48))
        #we render the template
        #from django.template import RequestContext
        questions_tpl = get_template('main_page/questions_loop.html', request)
        #todo: remove this patch on context after all templates are moved to jinja
        data = {
            'questions': page,
            'questions_count': q_count,
            'context': paginator_context,
            'language_code': translation.get_language(),
            'query': search_state.query,
            'reset_method_count': reset_method_count,
            'query_string': search_state.query_string(),
        }

        questions_html = questions_tpl.render(Context(data))
        #import pdb; pdb.set_trace()
        ajax_data['questions'] = questions_html.replace('\n','')
        return HttpResponse(
                    simplejson.dumps(ajax_data),
                    mimetype = 'application/json'
                )

    template_data = {
        'active_tab': 'questions',
        'author_name' : meta_data.get('author_name',None),
        'contributors' : contributors,
        'context' : paginator_context,
        'is_unanswered' : False,#remove this from template
        'interesting_tag_names': meta_data.get('interesting_tag_names',None),
        'ignored_tag_names': meta_data.get('ignored_tag_names',None),
        'language_code': translation.get_language(),
        'name_of_anonymous_user' : models.get_name_of_anonymous_user(),
        'page_class': 'main-page',
        'page_size': search_state.page_size,
        'query': search_state.query,
        'questions' : page,
        'questions_count' : paginator.count,
        'reset_method_count': reset_method_count,
        'scope': search_state.scope,
        'show_sort_by_relevance': askbot.conf.should_show_sort_by_relevance(),
        'search_tags' : search_state.tags,
        'sort': search_state.sort,
        'tab_id' : search_state.sort,
        'tags' : related_tags,
        'tag_list_type' : tag_list_type,
        'font_size' : font_size,
        'tag_filter_strategy_choices': const.TAG_FILTER_STRATEGY_CHOICES,
        'update_avatar_data': schedules.should_update_avatar_data(request),
        'query_string': search_state.query_string(),
        'parameters': search_state.make_parameters(),
        'feed_url': context_feed_url,
    }

    assert(request.is_ajax() == False)
    #ajax request is handled in a separate branch above

    #before = datetime.datetime.now()
    response = render_into_skin('main_page.html', template_data, request)
    #after = datetime.datetime.now()
    #print after - before
    return response
Beispiel #6
0
def questions(request, **kwargs):
    """
    List of Questions, Tagged questions, and Unanswered questions.
    matching search query or user selection
    """
    if request.method != 'GET':
        return HttpResponseNotAllowed(['GET'])

    search_state = SearchState(user_logged_in=request.user.is_authenticated(), **kwargs)

    #######

    page_size = int(askbot_settings.DEFAULT_QUESTIONS_PAGE_SIZE)

    qs, meta_data, related_tags = models.Thread.objects.run_advanced_search(request_user=request.user, search_state=search_state, page_size=page_size)

    tag_list_type = askbot_settings.TAG_LIST_FORMAT
    if tag_list_type == 'cloud': #force cloud to sort by name
        related_tags = sorted(related_tags, key = operator.attrgetter('name'))

    paginator = Paginator(qs, page_size)
    if paginator.num_pages < search_state.page:
        search_state.page = 1
    page = paginator.page(search_state.page)

    contributors_threads = models.Thread.objects.filter(id__in=[post.thread_id for post in page.object_list])
    contributors = models.Thread.objects.get_thread_contributors(contributors_threads)

    paginator_context = {
        'is_paginated' : (paginator.count > page_size),

        'pages': paginator.num_pages,
        'page': search_state.page,
        'has_previous': page.has_previous(),
        'has_next': page.has_next(),
        'previous': page.previous_page_number(),
        'next': page.next_page_number(),

        'base_url' : search_state.query_string(),#todo in T sort=>sort_method
        'page_size' : page_size,#todo in T pagesize -> page_size
    }

    # We need to pass the rss feed url based
    # on the search state to the template.
    # We use QueryDict to get a querystring
    # from dicts and arrays. Much cleaner
    # than parsing and string formating.
    rss_query_dict = QueryDict("").copy()
    if search_state.query:
        # We have search string in session - pass it to
        # the QueryDict
        rss_query_dict.update({"q": search_state.query})
    if search_state.tags:
        # We have tags in session - pass it to the
        # QueryDict but as a list - we want tags+
        rss_query_dict.setlist("tags", search_state.tags)
    context_feed_url = '/feeds/rss/?%s' % rss_query_dict.urlencode() # Format the url with the QueryDict

    reset_method_count = len(filter(None, [search_state.query, search_state.tags, meta_data.get('author_name', None)]))

    if request.is_ajax():
        q_count = paginator.count

        if search_state.tags:
            question_counter = ungettext('%(q_num)s question, tagged', '%(q_num)s questions, tagged', q_count)
        else:
            question_counter = ungettext('%(q_num)s question', '%(q_num)s questions', q_count)
        question_counter = question_counter % {'q_num': humanize.intcomma(q_count),}

        if q_count > page_size:
            paginator_tpl = get_template('main_page/paginator.html', request)
            paginator_html = paginator_tpl.render(Context({
                'context': functions.setup_paginator(paginator_context),
                'questions_count': q_count,
                'page_size' : page_size,
                'search_state': search_state,
            }))
        else:
            paginator_html = ''

        questions_tpl = get_template('main_page/questions_loop.html', request)
        questions_html = questions_tpl.render(Context({
            'questions': page,
            'search_state': search_state,
            'reset_method_count': reset_method_count,
        }))

        ajax_data = {
            'query_data': {
                'tags': search_state.tags,
                'sort_order': search_state.sort,
                'ask_query_string': search_state.ask_query_string(),
            },
            'paginator': paginator_html,
            'question_counter': question_counter,
            'questions': list(),
            'faces': [extra_tags.gravatar(contributor, 48) for contributor in contributors],
            'feed_url': context_feed_url,
            'query_string': search_state.query_string(),
            'page_size' : page_size,
            'questions': questions_html.replace('\n',''),
        }
        ajax_data['related_tags'] = [{
            'name': tag.name,
            'used_count': humanize.intcomma(tag.local_used_count)
        } for tag in related_tags]

        return HttpResponse(simplejson.dumps(ajax_data), mimetype = 'application/json')

    else: # non-AJAX branch

        template_data = {
            'active_tab': 'questions',
            'author_name' : meta_data.get('author_name',None),
            'contributors' : contributors,
            'context' : paginator_context,
            'is_unanswered' : False,#remove this from template
            'interesting_tag_names': meta_data.get('interesting_tag_names',None),
            'ignored_tag_names': meta_data.get('ignored_tag_names',None),
            'language_code': translation.get_language(),
            'name_of_anonymous_user' : models.get_name_of_anonymous_user(),
            'page_class': 'main-page',
            'page_size': page_size,
            'query': search_state.query,
            'questions' : page,
            'questions_count' : paginator.count,
            'reset_method_count': reset_method_count,
            'scope': search_state.scope,
            'show_sort_by_relevance': askbot.conf.should_show_sort_by_relevance(),
            'search_tags' : search_state.tags,
            'sort': search_state.sort,
            'tab_id' : search_state.sort,
            'tags' : related_tags,
            'tag_list_type' : tag_list_type,
            'font_size' : extra_tags.get_tag_font_size(related_tags),
            'tag_filter_strategy_choices': const.TAG_FILTER_STRATEGY_CHOICES,
            'update_avatar_data': schedules.should_update_avatar_data(request),
            'query_string': search_state.query_string(),
            'search_state': search_state,
            'feed_url': context_feed_url,
        }

        return render_into_skin('main_page.html', template_data, request)
Beispiel #7
0
def questions(request):
    """
    List of Questions, Tagged questions, and Unanswered questions.
    matching search query or user selection
    """
    # before = datetime.datetime.now()
    # don't allow to post to this view
    if request.method == "POST":
        raise Http404

    # update search state
    form = AdvancedSearchForm(request.GET)
    if form.is_valid():
        user_input = form.cleaned_data
    else:
        user_input = None
    search_state = request.session.get("search_state", SearchState())
    view_log = request.session["view_log"]
    search_state.update(user_input, view_log, request.user)
    request.session["search_state"] = search_state
    request.session.modified = True

    # force reset for debugging
    # search_state.reset()
    # request.session.modified = True

    # todo: have this call implemented for sphinx, mysql and pgsql
    (qs, meta_data, related_tags) = models.Question.objects.run_advanced_search(
        request_user=request.user, search_state=search_state
    )

    tag_list_type = askbot_settings.TAG_LIST_FORMAT

    # force cloud to sort by name
    if tag_list_type == "cloud":
        related_tags = sorted(related_tags, key=operator.attrgetter("name"))

    font_size = extra_tags.get_tag_font_size(related_tags)

    paginator = Paginator(qs, search_state.page_size)

    if paginator.num_pages < search_state.page:
        raise Http404

    page = paginator.page(search_state.page)

    contributors = models.Question.objects.get_question_and_answer_contributors(page.object_list)

    paginator_context = {
        "is_paginated": (paginator.count > search_state.page_size),
        "pages": paginator.num_pages,
        "page": search_state.page,
        "has_previous": page.has_previous(),
        "has_next": page.has_next(),
        "previous": page.previous_page_number(),
        "next": page.next_page_number(),
        "base_url": request.path + "?sort=%s&amp;" % search_state.sort,  # todo in T sort=>sort_method
        "page_size": search_state.page_size,  # todo in T pagesize -> page_size
    }

    if request.is_ajax():

        q_count = paginator.count
        if search_state.tags:
            question_counter = ungettext("%(q_num)s question, tagged", "%(q_num)s questions, tagged", q_count) % {
                "q_num": humanize.intcomma(q_count)
            }
        else:
            question_counter = ungettext("%(q_num)s question", "%(q_num)s questions", q_count) % {
                "q_num": humanize.intcomma(q_count)
            }

        if q_count > search_state.page_size:
            paginator_tpl = get_template("blocks/paginator.html", request)
            # todo: remove this patch on context after all templates are moved to jinja
            paginator_context["base_url"] = request.path + "?sort=%s&" % search_state.sort
            data = {"paginator_context": extra_tags.cnprog_paginator(paginator_context)}
            paginator_html = paginator_tpl.render(Context(data))
        else:
            paginator_html = ""
        search_tags = list()
        if search_state.tags:
            search_tags = list(search_state.tags)
        query_data = {"tags": search_tags, "sort_order": search_state.sort}
        ajax_data = {
            # current page is 1 by default now
            # because ajax is only called by update in the search button
            "query_data": query_data,
            "paginator": paginator_html,
            "question_counter": question_counter,
            "questions": list(),
            "related_tags": list(),
            "faces": list(),
        }

        badge_levels = dict(const.BADGE_TYPE_CHOICES)

        def pluralize_badge_count(count, level):
            return ungettext(
                "%(badge_count)d %(badge_level)s badge", "%(badge_count)d %(badge_level)s badges", count
            ) % {"badge_count": count, "badge_level": badge_levels[level]}

        gold_badge_css_class = (const.BADGE_CSS_CLASSES[const.GOLD_BADGE],)
        silver_badge_css_class = (const.BADGE_CSS_CLASSES[const.SILVER_BADGE],)
        bronze_badge_css_class = (const.BADGE_CSS_CLASSES[const.BRONZE_BADGE],)

        for tag in related_tags:
            tag_data = {"name": tag.name, "used_count": humanize.intcomma(tag.local_used_count)}
            ajax_data["related_tags"].append(tag_data)

        for contributor in contributors:
            ajax_data["faces"].append(extra_tags.gravatar(contributor, 48))

        for question in page.object_list:
            timestamp = question.last_activity_at
            author = question.last_activity_by

            if question.score == 0:
                votes_class = "no-votes"
            else:
                votes_class = "some-votes"

            if question.answer_count == 0:
                answers_class = "no-answers"
            elif question.answer_accepted:
                answers_class = "accepted"
            else:
                answers_class = "some-answers"

            if question.view_count == 0:
                views_class = "no-views"
            else:
                views_class = "some-views"

            country_code = None
            if author.country and author.show_country:
                country_code = author.country.code

            question_data = {
                "title": question.title,
                "summary": question.summary,
                "id": question.id,
                "tags": question.get_tag_names(),
                "tag_list_type": tag_list_type,
                "font_size": font_size,
                "votes": extra_filters.humanize_counter(question.score),
                "votes_class": votes_class,
                "votes_word": ungettext("vote", "votes", question.score),
                "answers": extra_filters.humanize_counter(question.answer_count),
                "answers_class": answers_class,
                "answers_word": ungettext("answer", "answers", question.answer_count),
                "views": extra_filters.humanize_counter(question.view_count),
                "views_class": views_class,
                "views_word": ungettext("view", "views", question.view_count),
                "timestamp": unicode(timestamp),
                "timesince": functions.diff_date(timestamp),
                "u_id": author.id,
                "u_name": author.username,
                "u_rep": author.reputation,
                "u_gold": author.gold,
                "u_gold_title": pluralize_badge_count(author.gold, const.GOLD_BADGE),
                "u_gold_badge_symbol": const.BADGE_DISPLAY_SYMBOL,
                "u_gold_css_class": gold_badge_css_class,
                "u_silver": author.silver,
                "u_silver_title": pluralize_badge_count(author.silver, const.SILVER_BADGE),
                "u_silver_badge_symbol": const.BADGE_DISPLAY_SYMBOL,
                "u_silver_css_class": silver_badge_css_class,
                "u_bronze": author.bronze,
                "u_bronze_title": pluralize_badge_count(author.bronze, const.BRONZE_BADGE),
                "u_bronze_badge_symbol": const.BADGE_DISPLAY_SYMBOL,
                "u_bronze_css_class": bronze_badge_css_class,
                "u_country_code": country_code,
                "u_is_anonymous": question.is_anonymous,
            }
            ajax_data["questions"].append(question_data)

        return HttpResponse(simplejson.dumps(ajax_data), mimetype="application/json")

    reset_method_count = 0
    if search_state.query:
        reset_method_count += 1
    if search_state.tags:
        reset_method_count += 1
    if meta_data.get("author_name", None):
        reset_method_count += 1

    template_data = {
        "active_tab": "questions",
        "author_name": meta_data.get("author_name", None),
        "contributors": contributors,
        "context": paginator_context,
        "is_unanswered": False,  # remove this from template
        "interesting_tag_names": meta_data.get("interesting_tag_names", None),
        "ignored_tag_names": meta_data.get("ignored_tag_names", None),
        "language_code": translation.get_language(),
        "name_of_anonymous_user": models.get_name_of_anonymous_user(),
        "page_class": "main-page",
        "query": search_state.query,
        "questions": page,
        "questions_count": paginator.count,
        "reset_method_count": reset_method_count,
        "scope": search_state.scope,
        "show_sort_by_relevance": askbot.conf.should_show_sort_by_relevance(),
        "search_tags": search_state.tags,
        "sort": search_state.sort,
        "tab_id": search_state.sort,
        "tags": related_tags,
        "tag_list_type": tag_list_type,
        "font_size": font_size,
        "tag_filter_strategy_choices": const.TAG_FILTER_STRATEGY_CHOICES,
        "update_avatar_data": schedules.should_update_avatar_data(request),
    }

    assert request.is_ajax() == False
    # ajax request is handled in a separate branch above

    # before = datetime.datetime.now()
    response = render_into_skin("main_page.html", template_data, request)
    # after = datetime.datetime.now()
    # print after - before
    return response
Beispiel #8
0
            'page_size': page_size,
            'query': search_state.query,
            'threads' : page,
            'questions_count' : paginator.count,
            'reset_method_count': reset_method_count,
            'scope': search_state.scope,
            'show_sort_by_relevance': conf.should_show_sort_by_relevance(),
            'search_tags' : search_state.tags,
            'sort': search_state.sort,
            'tab_id' : search_state.sort,
            'tags' : related_tags,
            'tag_list_type' : tag_list_type,
            'font_size' : extra_tags.get_tag_font_size(related_tags),
            'display_tag_filter_strategy_choices': conf.get_tag_display_filter_strategy_choices(),
            'email_tag_filter_strategy_choices': conf.get_tag_email_filter_strategy_choices(),
            'update_avatar_data': schedules.should_update_avatar_data(request),
            'query_string': search_state.query_string(),
            'search_state': search_state,
            'feed_url': context_feed_url,
        }

        extra_context = context.get_extra(
                                    'ASKBOT_QUESTIONS_PAGE_EXTRA_CONTEXT',
                                    request,
                                    template_data
                                )
        template_data.update(extra_context)

        return render(request, 'main_page.html', template_data)

Beispiel #9
0
def questions(request):
    """
    List of Questions, Tagged questions, and Unanswered questions.
    matching search query or user selection
    """
    #before = datetime.datetime.now()
    #don't allow to post to this view
    if request.method == 'POST':
        raise Http404

    #update search state
    form = AdvancedSearchForm(request.GET)
    if form.is_valid():
        user_input = form.cleaned_data
    else:
        user_input = None
    search_state = request.session.get('search_state', SearchState())
    view_log = request.session['view_log']
    search_state.update(user_input, view_log, request.user)
    request.session['search_state'] = search_state
    request.session.modified = True

    #force reset for debugging
    #search_state.reset()
    #request.session.modified = True

    #todo: have this call implemented for sphinx, mysql and pgsql
    (qs, meta_data, related_tags) = models.Question.objects.run_advanced_search(
                                            request_user = request.user,
                                            search_state = search_state,
                                        )

    tag_list_type = askbot_settings.TAG_LIST_FORMAT

    #force cloud to sort by name
    if tag_list_type == 'cloud':
        related_tags = sorted(related_tags, key = operator.attrgetter('name'))

    font_size = extra_tags.get_tag_font_size(related_tags)

    paginator = Paginator(qs, search_state.page_size)

    if paginator.num_pages < search_state.page:
        raise Http404

    page = paginator.page(search_state.page)

    contributors = models.Question.objects.get_question_and_answer_contributors(page.object_list)

    paginator_context = {
        'is_paginated' : (paginator.count > search_state.page_size),
        'pages': paginator.num_pages,
        'page': search_state.page,
        'has_previous': page.has_previous(),
        'has_next': page.has_next(),
        'previous': page.previous_page_number(),
        'next': page.next_page_number(),
        'base_url' : request.path + '?sort=%s&amp;' % search_state.sort,#todo in T sort=>sort_method
        'page_size' : search_state.page_size,#todo in T pagesize -> page_size
    }

    if request.is_ajax():

        q_count = paginator.count
        if search_state.tags:
            question_counter = ungettext(
                                    '%(q_num)s question, tagged',
                                    '%(q_num)s questions, tagged',
                                    q_count
                                ) % {
                                    'q_num': humanize.intcomma(q_count),
                                }
        else:
            question_counter = ungettext(
                                    '%(q_num)s question',
                                    '%(q_num)s questions',
                                    q_count
                                ) % {
                                    'q_num': humanize.intcomma(q_count),
                                }

        if q_count > search_state.page_size:
            paginator_tpl = get_template('main_page/paginator.html', request)
            #todo: remove this patch on context after all templates are moved to jinja
            paginator_context['base_url'] = request.path + '?sort=%s&' % search_state.sort
            data = {
                'context': extra_tags.cnprog_paginator(paginator_context),
                'questions_count': q_count
            }
            paginator_html = paginator_tpl.render(Context(data))
        else:
            paginator_html = ''
        search_tags = list()
        if search_state.tags:
            search_tags = list(search_state.tags)
        query_data = {
            'tags': search_tags,
            'sort_order': search_state.sort
        }
        ajax_data = {
            #current page is 1 by default now
            #because ajax is only called by update in the search button
            'query_data': query_data,
            'paginator': paginator_html,
            'question_counter': question_counter,
            'questions': list(),
            'related_tags': list(),
            'faces': list()
        }

        badge_levels = dict(const.BADGE_TYPE_CHOICES)
        def pluralize_badge_count(count, level):
            return ungettext(
                '%(badge_count)d %(badge_level)s badge',
                '%(badge_count)d %(badge_level)s badges',
                count
            ) % {
                'badge_count': count,
                'badge_level': badge_levels[level]
            }

        gold_badge_css_class = const.BADGE_CSS_CLASSES[const.GOLD_BADGE],
        silver_badge_css_class = const.BADGE_CSS_CLASSES[const.SILVER_BADGE],
        bronze_badge_css_class = const.BADGE_CSS_CLASSES[const.BRONZE_BADGE],

        for tag in related_tags:
            tag_data = {
                'name': tag.name,
                'used_count': humanize.intcomma(tag.local_used_count)
            }
            ajax_data['related_tags'].append(tag_data)

        for contributor in contributors:
            ajax_data['faces'].append(extra_tags.gravatar(contributor, 48))
        #we render the template
        #from django.template import RequestContext
        questions_tpl = get_template('main_page/questions_loop.html', request)
        #todo: remove this patch on context after all templates are moved to jinja
        data = {
            'questions': page,
            'questions_count': q_count,
            'context': paginator_context,
            'language_code': translation.get_language(),
            'query': search_state.query,
        }

        questions_html = questions_tpl.render(Context(data))
        ajax_data['questions'] = questions_html.replace('\n','')
        return HttpResponse(
                    simplejson.dumps(ajax_data),
                    mimetype = 'application/json'
                )

    reset_method_count = 0
    if search_state.query:
        reset_method_count += 1
    if search_state.tags:
        reset_method_count += 1
    if meta_data.get('author_name',None):
        reset_method_count += 1

    template_data = {
        'active_tab': 'questions',
        'author_name' : meta_data.get('author_name',None),
        'contributors' : contributors,
        'context' : paginator_context,
        'is_unanswered' : False,#remove this from template
        'interesting_tag_names': meta_data.get('interesting_tag_names',None),
        'ignored_tag_names': meta_data.get('ignored_tag_names',None),
        'language_code': translation.get_language(),
        'name_of_anonymous_user' : models.get_name_of_anonymous_user(),
        'page_class': 'main-page',
        'query': search_state.query,
        'questions' : page,
        'questions_count' : paginator.count,
        'reset_method_count': reset_method_count,
        'scope': search_state.scope,
        'show_sort_by_relevance': askbot.conf.should_show_sort_by_relevance(),
        'search_tags' : search_state.tags,
        'sort': search_state.sort,
        'tab_id' : search_state.sort,
        'tags' : related_tags,
        'tag_list_type' : tag_list_type,
        'font_size' : font_size,
        'tag_filter_strategy_choices': const.TAG_FILTER_STRATEGY_CHOICES,
        'update_avatar_data': schedules.should_update_avatar_data(request),
    }

    assert(request.is_ajax() == False)
    #ajax request is handled in a separate branch above

    #before = datetime.datetime.now()
    response = render_into_skin('main_page.html', template_data, request)
    #after = datetime.datetime.now()
    #print after - before
    return response
Beispiel #10
0
def questions(request):
    """
    List of Questions, Tagged questions, and Unanswered questions.
    matching search query or user selection
    """
    #before = datetime.datetime.now()
    #don't allow to post to this view
    if request.method == 'POST':
        raise Http404

    #update search state
    form = AdvancedSearchForm(request.GET)
    if form.is_valid():
        user_input = form.cleaned_data
    else:
        user_input = None
    search_state = request.session.get('search_state', SearchState())
    view_log = request.session['view_log']
    search_state.update(user_input, view_log, request.user)
    request.session['search_state'] = search_state
    request.session.modified = True

    #force reset for debugging
    #search_state.reset()
    #request.session.modified = True

    #todo: have this call implemented for sphinx, mysql and pgsql
    (qs, meta_data, related_tags) = models.Question.objects.run_advanced_search(
                                            request_user = request.user,
                                            search_state = search_state,
                                        )

    tag_list_type = askbot_settings.TAG_LIST_FORMAT
    
    #force cloud to sort by name
    if tag_list_type == 'cloud':
        related_tags = sorted(related_tags, key = operator.attrgetter('name'))

    font_size = extra_tags.get_tag_font_size(related_tags)
    
    paginator = Paginator(qs, search_state.page_size)

    if paginator.num_pages < search_state.page:
        raise Http404

    page = paginator.page(search_state.page)

    contributors = models.Question.objects.get_question_and_answer_contributors(page.object_list)

    paginator_context = {
        'is_paginated' : (paginator.count > search_state.page_size),
        'pages': paginator.num_pages,
        'page': search_state.page,
        'has_previous': page.has_previous(),
        'has_next': page.has_next(),
        'previous': page.previous_page_number(),
        'next': page.next_page_number(),
        'base_url' : request.path + '?sort=%s&amp;' % search_state.sort,#todo in T sort=>sort_method
        'page_size' : search_state.page_size,#todo in T pagesize -> page_size
    }

    if request.is_ajax():

        q_count = paginator.count
        if search_state.tags:
            question_counter = ungettext(
                                    '%(q_num)s question, tagged',
                                    '%(q_num)s questions, tagged',
                                    q_count
                                ) % {
                                    'q_num': humanize.intcomma(q_count),
                                }
        else:
            question_counter = ungettext(
                                    '%(q_num)s question',
                                    '%(q_num)s questions',
                                    q_count
                                ) % {
                                    'q_num': humanize.intcomma(q_count),
                                }

        if q_count > search_state.page_size:
            paginator_tpl = get_template('blocks/paginator.html', request)
            #todo: remove this patch on context after all templates are moved to jinja
            paginator_context['base_url'] = request.path + '?sort=%s&' % search_state.sort
            data = {
                'paginator_context': extra_tags.cnprog_paginator(paginator_context)
            }
            paginator_html = paginator_tpl.render(Context(data))
        else:
            paginator_html = ''
        search_tags = list()
        if search_state.tags:
            search_tags = list(search_state.tags)
        query_data = {
            'tags': search_tags,
            'sort_order': search_state.sort
        }
        ajax_data = {
            #current page is 1 by default now
            #because ajax is only called by update in the search button
            'query_data': query_data,
            'paginator': paginator_html,
            'question_counter': question_counter,
            'questions': list(),
            'related_tags': list(),
            'faces': list()
        }

        badge_levels = dict(const.BADGE_TYPE_CHOICES)
        def pluralize_badge_count(count, level):
            return ungettext(
                '%(badge_count)d %(badge_level)s badge',
                '%(badge_count)d %(badge_level)s badges',
                count
            ) % {
                'badge_count': count, 
                'badge_level': badge_levels[level]
            }

        gold_badge_css_class = const.BADGE_CSS_CLASSES[const.GOLD_BADGE],
        silver_badge_css_class = const.BADGE_CSS_CLASSES[const.SILVER_BADGE],
        bronze_badge_css_class = const.BADGE_CSS_CLASSES[const.BRONZE_BADGE],

        for tag in related_tags:
            tag_data = {
                'name': tag.name,
                'used_count': humanize.intcomma(tag.local_used_count)
            }
            ajax_data['related_tags'].append(tag_data)

        for contributor in contributors:
            ajax_data['faces'].append(extra_tags.gravatar(contributor, 48))

        for question in page.object_list:
            timestamp = question.last_activity_at
            author = question.last_activity_by

            if question.score == 0:
                votes_class = 'no-votes'
            else:
                votes_class = 'some-votes'

            if question.answer_count == 0:
                answers_class = 'no-answers'
            elif question.answer_accepted:
                answers_class = 'accepted'
            else:
                answers_class = 'some-answers'

            if question.view_count == 0:
                views_class = 'no-views'
            else:
                views_class = 'some-views'

            country_code = None
            if author.country and author.show_country:
                country_code = author.country.code

            question_data = {
                'title': question.title,
                'id': question.id,
                'tags': question.get_tag_names(),
                'tag_list_type': tag_list_type,
                'font_size': font_size,
                'votes': extra_filters.humanize_counter(question.score),
                'votes_class': votes_class,
                'votes_word': ungettext('vote', 'votes', question.score),
                'answers': extra_filters.humanize_counter(question.answer_count),
                'answers_class': answers_class,
                'answers_word': ungettext('answer', 'answers', question.answer_count),
                'views': extra_filters.humanize_counter(question.view_count),
                'views_class': views_class,
                'views_word': ungettext('view', 'views', question.view_count),
                'timestamp': unicode(timestamp),
                'timesince': functions.diff_date(timestamp),
                'u_id': author.id,
                'u_name': author.username,
                'u_rep': author.reputation,
                'u_gold': author.gold,
                'u_gold_title': pluralize_badge_count(
                                                author.gold,
                                                const.GOLD_BADGE
                                            ),
                'u_gold_badge_symbol': const.BADGE_DISPLAY_SYMBOL,
                'u_gold_css_class': gold_badge_css_class,
                'u_silver': author.silver,
                'u_silver_title': pluralize_badge_count(
                                            author.silver,
                                            const.SILVER_BADGE
                                        ),
                'u_silver_badge_symbol': const.BADGE_DISPLAY_SYMBOL,
                'u_silver_css_class': silver_badge_css_class,
                'u_bronze': author.bronze,
                'u_bronze_title': pluralize_badge_count(
                                            author.bronze,
                                            const.BRONZE_BADGE
                                        ),
                'u_bronze_badge_symbol': const.BADGE_DISPLAY_SYMBOL,
                'u_bronze_css_class': bronze_badge_css_class,
                'u_country_code': country_code,
                'u_is_anonymous': question.is_anonymous,
            }
            ajax_data['questions'].append(question_data)

        return HttpResponse(
                    simplejson.dumps(ajax_data),
                    mimetype = 'application/json'
                )

    reset_method_count = 0
    if search_state.query:
        reset_method_count += 1
    if search_state.tags:
        reset_method_count += 1
    if meta_data.get('author_name',None):
        reset_method_count += 1

    template_data = {
        'active_tab': 'questions',
        'author_name' : meta_data.get('author_name',None),
        'contributors' : contributors,
        'context' : paginator_context,
        'is_unanswered' : False,#remove this from template
        'interesting_tag_names': meta_data.get('interesting_tag_names',None),
        'ignored_tag_names': meta_data.get('ignored_tag_names',None), 
        'language_code': translation.get_language(),
        'name_of_anonymous_user' : models.get_name_of_anonymous_user(),
        'page_class': 'main-page',
        'query': search_state.query,
        'questions' : page,
        'questions_count' : paginator.count,
        'reset_method_count': reset_method_count,
        'scope': search_state.scope,
        'show_sort_by_relevance': askbot.conf.should_show_sort_by_relevance(),
        'search_tags' : search_state.tags,
        'sort': search_state.sort,
        'tab_id' : search_state.sort,
        'tags' : related_tags,
        'tag_list_type' : tag_list_type,
        'font_size' : font_size,
        'tag_filter_strategy_choices': const.TAG_FILTER_STRATEGY_CHOICES,
        'update_avatar_data': schedules.should_update_avatar_data(request),
    }

    assert(request.is_ajax() == False)
    #ajax request is handled in a separate branch above

    #before = datetime.datetime.now()
    response = render_into_skin('main_page.html', template_data, request)
    #after = datetime.datetime.now()
    #print after - before
    return response
Beispiel #11
0
def questions(request, **kwargs):
    """
    List of Questions, Tagged questions, and Unanswered questions.
    matching search query or user selection
    """
    #before = datetime.datetime.now()
    if request.method != 'GET':
        return HttpResponseNotAllowed(['GET'])

    search_state = SearchState(user_logged_in=request.user.is_authenticated(),
                               **kwargs)

    qs, meta_data = models.Thread.objects.run_advanced_search(
        request_user=request.user, search_state=search_state)
    if meta_data['non_existing_tags']:
        search_state = search_state.remove_tags(meta_data['non_existing_tags'])

    paginator = Paginator(qs, search_state.page_size)
    if paginator.num_pages < search_state.page:
        search_state.page = 1
    page = paginator.page(search_state.page)
    page.object_list = list(page.object_list)  # evaluate the queryset

    # INFO: Because for the time being we need question posts and thread authors
    #       down the pipeline, we have to precache them in thread objects
    models.Thread.objects.precache_view_data_hack(threads=page.object_list)

    related_tags = Tag.objects.get_related_to_search(
        threads=page.object_list,
        ignored_tag_names=meta_data.get('ignored_tag_names', []))
    tag_list_type = askbot_settings.TAG_LIST_FORMAT
    if tag_list_type == 'cloud':  #force cloud to sort by name
        related_tags = sorted(related_tags, key=operator.attrgetter('name'))

    contributors = list(
        models.Thread.objects.get_thread_contributors(
            thread_list=page.object_list).only('id', 'username', 'gravatar'))

    paginator_context = {
        'is_paginated': (paginator.count > search_state.page_size),
        'pages': paginator.num_pages,
        'current_page_number': search_state.page,
        'page_object': page,
        'base_url': search_state.query_string(),
        'page_size': search_state.page_size,
    }

    # We need to pass the rss feed url based
    # on the search state to the template.
    # We use QueryDict to get a querystring
    # from dicts and arrays. Much cleaner
    # than parsing and string formating.
    rss_query_dict = QueryDict("").copy()
    if search_state.query:
        # We have search string in session - pass it to
        # the QueryDict
        rss_query_dict.update({"q": search_state.query})
    if search_state.tags:
        # We have tags in session - pass it to the
        # QueryDict but as a list - we want tags+
        rss_query_dict.setlist("tags", search_state.tags)
    context_feed_url = '/%sfeeds/rss/?%s' % (
        django_settings.ASKBOT_URL, rss_query_dict.urlencode()
    )  # Format the url with the QueryDict

    reset_method_count = len(
        filter(None, [
            search_state.query, search_state.tags,
            meta_data.get('author_name', None)
        ]))

    if request.is_ajax():
        q_count = paginator.count

        #todo: words
        question_counter = ungettext('%(q_num)s question',
                                     '%(q_num)s questions', q_count)
        question_counter = question_counter % {
            'q_num': humanize.intcomma(q_count),
        }

        if q_count > search_state.page_size:
            paginator_tpl = get_template('main_page/paginator.html')
            paginator_html = paginator_tpl.render(
                RequestContext(
                    request, {
                        'context': paginator_context,
                        'questions_count': q_count,
                        'page_size': search_state.page_size,
                        'search_state': search_state,
                    }))
        else:
            paginator_html = ''

        questions_tpl = get_template('main_page/questions_loop.html')
        questions_html = questions_tpl.render(
            RequestContext(
                request, {
                    'threads': page,
                    'search_state': search_state,
                    'reset_method_count': reset_method_count,
                    'request': request
                }))

        ajax_data = {
            'query_data': {
                'tags': search_state.tags,
                'sort_order': search_state.sort,
                'ask_query_string': search_state.ask_query_string(),
            },
            'paginator': paginator_html,
            'question_counter': question_counter,
            'faces':
            [],  #[extra_tags.gravatar(contributor, 48) for contributor in contributors],
            'feed_url': context_feed_url,
            'query_string': search_state.query_string(),
            'page_size': search_state.page_size,
            'questions': questions_html.replace('\n', ''),
            'non_existing_tags': meta_data['non_existing_tags'],
        }
        ajax_data['related_tags'] = [{
            'name':
            escape(tag.name),
            'used_count':
            humanize.intcomma(tag.local_used_count)
        } for tag in related_tags]

        #here we add and then delete some items
        #to allow extra context processor to work
        ajax_data['tags'] = related_tags
        ajax_data['interesting_tag_names'] = None
        ajax_data['threads'] = page
        extra_context = context.get_extra(
            'ASKBOT_QUESTIONS_PAGE_EXTRA_CONTEXT', request, ajax_data)
        del ajax_data['tags']
        del ajax_data['interesting_tag_names']
        del ajax_data['threads']

        ajax_data.update(extra_context)

        return HttpResponse(simplejson.dumps(ajax_data),
                            mimetype='application/json')

    else:  # non-AJAX branch

        template_data = {
            'active_tab':
            'questions',
            'author_name':
            meta_data.get('author_name', None),
            'contributors':
            contributors,
            'context':
            paginator_context,
            'is_unanswered':
            False,  #remove this from template
            'interesting_tag_names':
            meta_data.get('interesting_tag_names', None),
            'ignored_tag_names':
            meta_data.get('ignored_tag_names', None),
            'subscribed_tag_names':
            meta_data.get('subscribed_tag_names', None),
            'language_code':
            translation.get_language(),
            'name_of_anonymous_user':
            models.get_name_of_anonymous_user(),
            'page_class':
            'main-page',
            'page_size':
            search_state.page_size,
            'query':
            search_state.query,
            'threads':
            page,
            'questions_count':
            paginator.count,
            'reset_method_count':
            reset_method_count,
            'scope':
            search_state.scope,
            'show_sort_by_relevance':
            conf.should_show_sort_by_relevance(),
            'search_tags':
            search_state.tags,
            'sort':
            search_state.sort,
            'tab_id':
            search_state.sort,
            'tags':
            related_tags,
            'tag_list_type':
            tag_list_type,
            'font_size':
            extra_tags.get_tag_font_size(related_tags),
            'display_tag_filter_strategy_choices':
            conf.get_tag_display_filter_strategy_choices(),
            'email_tag_filter_strategy_choices':
            conf.get_tag_email_filter_strategy_choices(),
            'update_avatar_data':
            schedules.should_update_avatar_data(request),
            'query_string':
            search_state.query_string(),
            'search_state':
            search_state,
            'feed_url':
            context_feed_url,
        }

        extra_context = context.get_extra(
            'ASKBOT_QUESTIONS_PAGE_EXTRA_CONTEXT', request, template_data)

        template_data.update(extra_context)
        template_data.update(context.get_for_tag_editor())

        #and one more thing:) give admin user heads up about
        #setting the domain name if they have not done that yet
        #todo: move this out to a separate middleware
        if request.user.is_authenticated() and request.user.is_administrator():
            if domain_is_bad():
                url = reverse('group_settings',
                              kwargs={'group': 'QA_SITE_SETTINGS'})
                url = url + '#id_QA_SITE_SETTINGS__APP_URL'
                msg = _(
                    'Please go to '
                    '<a href="%s">"settings->URLs, keywords and greetings"</a> '
                    'and set the base url for your site to function properly'
                ) % url
                request.user.message_set.create(message=msg)

        return render(request, 'main_page.html', template_data)