예제 #1
0
def edit_comment(request):
    if request.user.is_anonymous():
        raise exceptions.PermissionDenied(_("Sorry, anonymous users cannot edit comments"))

    comment_id = int(request.POST["comment_id"])
    comment_post = models.Post.objects.get(post_type="comment", id=comment_id)

    request.user.edit_comment(comment_post=comment_post, body_text=request.POST["comment"])

    is_deletable = template_filters.can_delete_comment(comment_post.author, comment_post)
    is_editable = template_filters.can_edit_comment(comment_post.author, comment_post)

    return {
        "id": comment_post.id,
        "object_id": comment_post.parent.id,
        "comment_age": diff_date(comment_post.added_at),
        "html": comment_post.html,
        "user_display_name": comment_post.author.username,
        "user_url": comment_post.author.get_profile_url(),
        "user_id": comment_post.author.id,
        "is_deletable": is_deletable,
        "is_editable": is_editable,
        "score": comment_post.score,
        "voted": comment_post.is_upvoted_by(request.user),
    }
예제 #2
0
def edit_comment(request):
    if request.user.is_authenticated():
        comment_id = int(request.POST['comment_id'])
        comment = models.Comment.objects.get(id=comment_id)

        request.user.edit_comment(comment=comment,
                                  body_text=request.POST['comment'])

        is_deletable = template_filters.can_delete_comment(
            comment.user, comment)
        is_editable = template_filters.can_edit_comment(comment.user, comment)

        return {
            'id': comment.id,
            'object_id': comment.content_object.id,
            'comment_age': diff_date(comment.added_at),
            'html': comment.html,
            'user_display_name': comment.user.username,
            'user_url': comment.user.get_profile_url(),
            'user_id': comment.user.id,
            'is_deletable': is_deletable,
            'is_editable': is_editable,
        }
    else:
        raise exceptions.PermissionDenied(
            _('Sorry, anonymous users cannot edit comments'))
예제 #3
0
파일: writers.py 프로젝트: kazeevn/botan
def edit_comment(request):
    if request.user.is_authenticated():
        comment_id = int(request.POST['comment_id'])
        comment = models.Comment.objects.get(id = comment_id)

        request.user.edit_comment(
                        comment = comment,
                        body_text = request.POST['comment']
                    )

        is_deletable = template_filters.can_delete_comment(comment.user, comment)
        is_editable = template_filters.can_edit_comment(comment.user, comment)

        return {'id' : comment.id,
            'object_id': comment.content_object.id,
            'comment_age': diff_date(comment.added_at),
            'html': comment.html,
            'user_display_name': comment.user.username,
            'user_url': comment.user.get_profile_url(),
            'user_id': comment.user.id,
            'is_deletable': is_deletable,
            'is_editable': is_editable,
            'score': comment.score,
            'voted': comment.is_upvoted_by(request.user),
        }
    else:
        raise exceptions.PermissionDenied(
                _('Sorry, anonymous users cannot edit comments')
            )
예제 #4
0
def __generate_comments_json(
        obj, user):  #non-view generates json data for the post comments
    """non-view generates json data for the post comments
    """
    comments = obj.get_comments(visitor=user)
    # {"Id":6,"PostId":38589,"CreationDate":"an hour ago","Text":"hello there!","UserDisplayName":"Jarrod Dixon","UserUrl":"/users/3/jarrod-dixon","DeleteUrl":null}
    json_comments = []
    for comment in comments:

        if user != None and user.is_authenticated():
            try:
                user.assert_can_delete_comment(comment)
                #/posts/392845/comments/219852/delete
                #todo translate this url
                is_deletable = True
            except exceptions.PermissionDenied:
                is_deletable = False
            is_editable = template_filters.can_edit_comment(
                comment.user, comment)
        else:
            is_deletable = False
            is_editable = False

        comment_owner = comment.get_owner()
        comment_data = {
            'id': comment.id,
            'object_id': obj.id,
            'comment_age': diff_date(comment.added_at),
            'html': comment.html,
            'user_display_name': comment_owner.username,
            'user_url': comment_owner.get_profile_url(),
            'user_id': comment_owner.id,
            'is_deletable': is_deletable,
            'is_editable': is_editable,
            'score': comment.score,
            'upvoted_by_user': getattr(comment, 'upvoted_by_user', False)
        }
        json_comments.append(comment_data)

    data = simplejson.dumps(json_comments)
    return HttpResponse(data, mimetype="application/json")
예제 #5
0
def __generate_comments_json(obj, user):#non-view generates json data for the post comments
    """non-view generates json data for the post comments
    """
    models.Post.objects.precache_comments(for_posts=[obj], visitor=user)
    comments = obj._cached_comments

    # {"Id":6,"PostId":38589,"CreationDate":"an hour ago","Text":"hello there!","UserDisplayName":"Jarrod Dixon","UserUrl":"/users/3/jarrod-dixon","DeleteUrl":null}
    json_comments = []
    for comment in comments:

        if user and user.is_authenticated():
            try:
                user.assert_can_delete_comment(comment)
                #/posts/392845/comments/219852/delete
                #todo translate this url
                is_deletable = True
            except exceptions.PermissionDenied:
                is_deletable = False
            is_editable = template_filters.can_edit_comment(comment.author, comment)
        else:
            is_deletable = False
            is_editable = False


        comment_owner = comment.author
        comment_data = {'id' : comment.id,
            'object_id': obj.id,
            'comment_age': diff_date(comment.added_at),
            'html': comment.html,
            'user_display_name': comment_owner.username,
            'user_url': comment_owner.get_profile_url(),
            'user_id': comment_owner.id,
            'is_deletable': is_deletable,
            'is_editable': is_editable,
            'score': comment.score,
            'upvoted_by_user': getattr(comment, 'upvoted_by_user', False)
        }
        json_comments.append(comment_data)

    data = simplejson.dumps(json_comments)
    return HttpResponse(data, mimetype="application/json")
예제 #6
0
def __generate_comments_json(obj, user):  # non-view generates json data for the post comments
    """non-view generates json data for the post comments
    """
    comments = obj.comments.all().order_by("id")
    # {"Id":6,"PostId":38589,"CreationDate":"an hour ago","Text":"hello there!","UserDisplayName":"Jarrod Dixon","UserUrl":"/users/3/jarrod-dixon","DeleteUrl":null}
    json_comments = []
    for comment in comments:

        if user != None and user.is_authenticated():
            try:
                user.assert_can_delete_comment(comment)
                # /posts/392845/comments/219852/delete
                # todo translate this url
                is_deletable = True
            except exceptions.PermissionDenied:
                is_deletable = False
            is_editable = template_filters.can_edit_comment(comment.user, comment)
        else:
            is_deletable = False
            is_editable = False

        comment_owner = comment.get_owner()
        json_comments.append(
            {
                "id": comment.id,
                "object_id": obj.id,
                "comment_age": diff_date(comment.added_at),
                "html": comment.html,
                "user_display_name": comment_owner.username,
                "user_url": comment_owner.get_profile_url(),
                "user_id": comment_owner.id,
                "is_deletable": is_deletable,
                "is_editable": is_editable,
            }
        )

    data = simplejson.dumps(json_comments)
    return HttpResponse(data, mimetype="application/json")
예제 #7
0
def edit_comment(request):
    if request.user.is_authenticated():
        comment_id = int(request.POST["comment_id"])
        comment = models.Comment.objects.get(id=comment_id)

        request.user.edit_comment(comment=comment, body_text=request.POST["comment"])

        is_deletable = template_filters.can_delete_comment(comment.user, comment)
        is_editable = template_filters.can_edit_comment(comment.user, comment)

        return {
            "id": comment.id,
            "object_id": comment.content_object.id,
            "comment_age": diff_date(comment.added_at),
            "html": comment.html,
            "user_display_name": comment.user.username,
            "user_url": comment.user.get_profile_url(),
            "user_id": comment.user.id,
            "is_deletable": is_deletable,
            "is_editable": is_editable,
        }
    else:
        raise exceptions.PermissionDenied(_("Sorry, anonymous users cannot edit comments"))
예제 #8
0
def questions(request):
    """
    List of Questions, Tagged questions, and Unanswered questions.
    matching search query or user selection
    """
    #don't allow to post to this view
    if request.method == 'POST':
        raise Http404

    #todo: redo SearchState to accept input from
    #view_log, session and request parameters
    search_state = request.session.get('search_state', SearchState())

    view_log = request.session['view_log']

    if view_log.get_previous(1) != 'questions':
        if view_log.get_previous(2) != 'questions':
            #print 'user stepped too far, resetting search state'
            search_state.reset()

    if request.user.is_authenticated():
        search_state.set_logged_in()

    form = AdvancedSearchForm(request.GET)
    #todo: form is used only for validation...
    if form.is_valid():
        search_state.update_from_user_input(
                                    form.cleaned_data,
                                    request.GET,
                                )
        #todo: better put these in separately then analyze
        #what neesd to be done, otherwise there are two routines
        #that take request.GET I don't like this use of parameters
        #another weakness is that order of routine calls matters here
        search_state.relax_stickiness( request.GET, view_log )

        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,
                                        )

    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
        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 = ENV.get_template('paginator.html')
            #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 = ''
        ajax_data = {
            #current page is 1 by default now
            #because ajax is only called by update in the search button
            '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'

            question_data = {
                'title': question.title,
                'summary': question.summary,
                'id': question.id,
                'tags': question.get_tag_names(),
                '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,
            }
            ajax_data['questions'].append(question_data)

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

    tags_autocomplete = _get_tags_cache_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_context = RequestContext(request, {
        'language_code': translation.get_language(),
        'reset_method_count': reset_method_count,
        'view_name': 'questions',
        'active_tab': 'questions',
        'questions' : page,
        'contributors' : contributors,
        'author_name' : meta_data.get('author_name',None),
        'tab_id' : search_state.sort,
        'questions_count' : paginator.count,
        'tags' : related_tags,
        'query': search_state.query,
        'search_tags' : search_state.tags,
        'tags_autocomplete' : tags_autocomplete,
        '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), 
        'sort': search_state.sort,
        'show_sort_by_relevance': askbot.conf.should_show_sort_by_relevance(),
        'scope': search_state.scope,
        'context' : paginator_context,
    })

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

    #before = datetime.datetime.now()
    template = ENV.get_template('questions.html')
    response = HttpResponse(template.render(template_context))
    #after = datetime.datetime.now()
    #print after - before
    return response
예제 #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,
     )

    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(),
                '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_filter_strategy_choices': const.TAG_FILTER_STRATEGY_CHOICES,
    }

    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
예제 #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,
                '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,
    }

    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
예제 #11
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