コード例 #1
0
ファイル: users.py プロジェクト: sumeshcjacob/keralaentrance
def user_profile(request, user, **kwargs):
    questions = Question.objects.filter_state(deleted=False).filter(author=user).order_by('-added_at')
    answers = Answer.objects.filter_state(deleted=False).filter(author=user).order_by('-added_at')

    # Check whether the passed slug matches the one for the user object
    slug = kwargs['slug']
    if slug != slugify(smart_unicode(user.username)):
        return HttpResponseRedirect(user.get_absolute_url())

    up_votes = user.vote_up_count
    down_votes = user.vote_down_count
    votes_today = user.get_vote_count_today()
    votes_total = user.can_vote_count_today()

    user_tags = Tag.objects.filter(Q(nodes__author=user) | Q(nodes__children__author=user)) \
        .annotate(user_tag_usage_count=Count('name')).order_by('-user_tag_usage_count')

    awards = [(Badge.objects.get(id=b['id']), b['count']) for b in
              Badge.objects.filter(awards__user=user).values('id').annotate(count=Count('cls')).order_by('-count')]

    return pagination.paginated(request, (
    ('questions', QuestionListPaginatorContext('USER_QUESTION_LIST', _('questions'), default_pagesize=15)),
    ('answers', UserAnswersPaginatorContext())), {
    "view_user" : user,
    "questions" : questions,
    "answers" : answers,
    "up_votes" : up_votes,
    "down_votes" : down_votes,
    "total_votes": up_votes + down_votes,
    "votes_today_left": votes_total-votes_today,
    "votes_total_per_day": votes_total,
    "user_tags" : user_tags[:50],
    "awards": awards,
    "total_awards" : len(awards),
    })
コード例 #2
0
ファイル: users.py プロジェクト: isabella232/civipedia
def user_profile(request, user):
    questions = Question.objects.filter_state(deleted=False).filter(author=user).order_by('-added_at')
    answers = Answer.objects.filter_state(deleted=False).filter(author=user).order_by('-added_at')

    up_votes = user.vote_up_count
    down_votes = user.vote_down_count
    votes_today = user.get_vote_count_today()
    votes_total = int(settings.MAX_VOTES_PER_DAY)

    user_tags = Tag.objects.filter(Q(nodes__author=user) | Q(nodes__children__author=user)) \
        .annotate(user_tag_usage_count=Count('name')).order_by('-user_tag_usage_count')

    awards = [(Badge.objects.get(id=b['id']), b['count']) for b in
              Badge.objects.filter(awards__user=user).values('id').annotate(count=Count('cls')).order_by('-count')]

    return pagination.paginated(request, (
    ('questions', QuestionListPaginatorContext('USER_QUESTION_LIST', _('questions'), 15)),
    ('answers', UserAnswersPaginatorContext())), {
    "view_user" : user,
    "questions" : questions,
    "answers" : answers,
    "up_votes" : up_votes,
    "down_votes" : down_votes,
    "total_votes": up_votes + down_votes,
    "votes_today_left": votes_total-votes_today,
    "votes_total_per_day": votes_total,
    "user_tags" : user_tags[:50],
    "awards": awards,
    "total_awards" : len(awards),
    })
コード例 #3
0
def dashboard(request):
    return ('osqaadmin/dashboard.html', pagination.paginated(request, ("recent_activity", ActivityPaginatorContext()), {
    'settings_pack': unicode(settings.SETTINGS_PACK),
    'statistics': get_statistics(),
    'recent_activity': get_recent_activity(),
    'flagged_posts': get_flagged_posts(),
    }))
コード例 #4
0
ファイル: readers.py プロジェクト: nickpack/OSQA
def question_list(
    request,
    initial,
    list_description=_("questions"),
    base_path=None,
    page_title=_("All Questions"),
    allowIgnoreTags=True,
    feed_url=None,
    paginator_context=None,
    show_summary=None,
    feed_sort=("-added_at",),
    feed_req_params_exclude=(_("page"), _("pagesize"), _("sort")),
    extra_context={},
):

    if show_summary is None:
        show_summary = bool(settings.SHOW_SUMMARY_ON_QUESTIONS_LIST)

    questions = initial.filter_state(deleted=False)

    if request.user.is_authenticated() and allowIgnoreTags:
        questions = questions.filter(~Q(tags__id__in=request.user.marked_tags.filter(user_selections__reason="bad")))

    if page_title is None:
        page_title = _("Questions")

    if request.GET.get("type", None) == "rss":
        if feed_sort:
            questions = questions.order_by(*feed_sort)
        return RssQuestionFeed(request, questions, page_title, list_description)(request)

    keywords = ""
    if request.GET.get("q"):
        keywords = request.GET.get("q").strip()

    # answer_count = Answer.objects.filter_state(deleted=False).filter(parent__in=questions).count()
    # answer_description = _("answers")

    if not feed_url:
        req_params = generate_uri(request.GET, feed_req_params_exclude)

        if req_params:
            req_params = "&" + req_params

        feed_url = request.path + "?type=rss" + req_params

    context = {
        "questions": questions.distinct(),
        "questions_count": questions.count(),
        "keywords": keywords,
        "list_description": list_description,
        "base_path": base_path,
        "page_title": page_title,
        "tab": "questions",
        "feed_url": feed_url,
        "show_summary": show_summary,
    }
    context.update(extra_context)

    return pagination.paginated(request, ("questions", paginator_context or QuestionListPaginatorContext()), context)
コード例 #5
0
ファイル: users.py プロジェクト: theStuff/OSQASrc
def user_profile(request, user, **kwargs):
    questions = Question.objects.filter_state(deleted=False).filter(author=user).order_by('-added_at')
    answers = Answer.objects.filter_state(deleted=False).filter(author=user).order_by('-added_at')

    # Check whether the passed slug matches the one for the user object
    slug = kwargs['slug']
    if slug != slugify(smart_unicode(user.username)):
        return HttpResponseRedirect(user.get_absolute_url())

    up_votes = user.vote_up_count
    down_votes = user.vote_down_count
    votes_today = user.get_vote_count_today()
    votes_total = user.can_vote_count_today()

    user_tags = Tag.objects.filter(Q(nodes__author=user) | Q(nodes__children__author=user)) \
        .annotate(user_tag_usage_count=Count('name')).order_by('-user_tag_usage_count')

    awards = [(Badge.objects.get(id=b['id']), b['count']) for b in
              Badge.objects.filter(awards__user=user).values('id').annotate(count=Count('cls')).order_by('-count')]

    return pagination.paginated(request, (
    ('questions', QuestionListPaginatorContext('USER_QUESTION_LIST', _('questions'), default_pagesize=15)),
    ('answers', UserAnswersPaginatorContext())), {
    "view_user" : user,
    "questions" : questions,
    "answers" : answers,
    "up_votes" : up_votes,
    "down_votes" : down_votes,
    "total_votes": up_votes + down_votes,
    "votes_today_left": votes_total-votes_today,
    "votes_total_per_day": votes_total,
    "user_tags" : user_tags[:50],
    "awards": awards,
    "total_awards" : len(awards),
    })
コード例 #6
0
ファイル: users.py プロジェクト: teknolab/teknolab-osqa
def user_profile(request, user):
    questions = Question.objects.filter_state(deleted=False).filter(author=user).order_by('-added_at')
    answers = Answer.objects.filter_state(deleted=False).filter(author=user).order_by('-added_at')

    up_votes = user.vote_up_count
    down_votes = user.vote_down_count
    votes_today = user.get_vote_count_today()
    votes_total = int(settings.MAX_VOTES_PER_DAY)

    user_tags = Tag.objects.filter(Q(nodes__author=user) | Q(nodes__children__author=user)) \
        .annotate(user_tag_usage_count=Count('name')).order_by('-user_tag_usage_count')

    awards = [(Badge.objects.get(id=b['id']), b['count']) for b in
              Badge.objects.filter(awards__user=user).values('id').annotate(count=Count('cls')).order_by('-count')]

    return pagination.paginated(request, (
    ('questions', QuestionListPaginatorContext('USER_QUESTION_LIST', _('questions'), 15)),
    ('answers', UserAnswersPaginatorContext())), {
    "view_user" : user,
    "questions" : questions,
    "answers" : answers,
    "up_votes" : up_votes,
    "down_votes" : down_votes,
    "total_votes": up_votes + down_votes,
    "votes_today_left": votes_total-votes_today,
    "votes_total_per_day": votes_total,
    "user_tags" : user_tags[:50],
    "awards": awards,
    "total_awards" : len(awards),
    })
コード例 #7
0
def user_subscriptions(request, user):
    enabled = user.subscription_settings.enable_notifications

    tab = request.GET.get('tab', "settings")

    if tab == 'settings':
        manage_open = False
        if request.method == 'POST':
            manage_open = False
            form = SubscriptionSettingsForm(
                data=request.POST, instance=user.subscription_settings)

            if form.is_valid():
                form.save()
                message = _('New subscription settings are now saved')

                if 'notswitch' in request.POST:
                    enabled = not enabled

                    if enabled:
                        message = _('Notifications are now enabled')
                    else:
                        message = _('Notifications are now disabled')

                user.subscription_settings.enable_notifications = enabled
                user.subscription_settings.save()

                request.user.message_set.create(message=message)
        else:
            form = SubscriptionSettingsForm(
                instance=user.subscription_settings)

        return {
            'view_user': user,
            'notificatons_on': enabled,
            'form': form,
            'manage_open': manage_open,
        }

    elif tab == 'manage':
        manage_open = True

        auto = request.GET.get('auto', 'True')
        if auto == 'True':
            show_auto = True
            subscriptions = QuestionSubscription.objects.filter(
                user=user).order_by('-last_view')
        else:
            show_auto = False
            subscriptions = QuestionSubscription.objects.filter(
                user=user, auto_subscription=False).order_by('-last_view')

        return pagination.paginated(
            request, ('subscriptions', SubscriptionListPaginatorContext()), {
                'subscriptions': subscriptions,
                'view_user': user,
                "auto": show_auto,
                'manage_open': manage_open,
            })
コード例 #8
0
ファイル: readers.py プロジェクト: softbalajibi/osqa
def question_list(request, initial,
                  list_description=_('questions'),
                  base_path=None,
                  page_title=_("All Questions"),
                  allowIgnoreTags=True,
                  feed_url=None,
                  paginator_context=None,
                  show_summary=None,
                  feed_sort=('-added_at',),
                  feed_req_params_exclude=(_('page'), _('pagesize'), _('sort')),
                  extra_context={}):

    if show_summary is None:
        show_summary = bool(settings.SHOW_SUMMARY_ON_QUESTIONS_LIST)

    questions = initial.filter_state(deleted=False)

    if request.user.is_authenticated() and allowIgnoreTags:
        questions = questions.filter(~Q(tags__id__in = request.user.marked_tags.filter(user_selections__reason = 'bad')))

    if page_title is None:
        page_title = _("Questions")

    if request.GET.get('type', None) == 'rss':
        if feed_sort:
            questions = questions.order_by(*feed_sort)
        return RssQuestionFeed(request, questions, page_title, list_description)(request)

    keywords =  ""
    if request.GET.get("q"):
        keywords = request.GET.get("q").strip()

    #answer_count = Answer.objects.filter_state(deleted=False).filter(parent__in=questions).count()
    #answer_description = _("answers")

    if not feed_url:
        req_params = generate_uri(request.GET, feed_req_params_exclude)

        if req_params:
            req_params = '&' + req_params

        feed_url = request.path + "?type=rss" + req_params

    context = {
        'questions' : questions.distinct(),
        'questions_count' : questions.count(),
        'keywords' : keywords,
        'list_description': list_description,
        'base_path' : base_path,
        'page_title' : page_title,
        'tab' : 'questions',
        'feed_url': feed_url,
        'show_summary' : show_summary,
    }
    context.update(extra_context)

    return pagination.paginated(request,
                               ('questions', paginator_context or QuestionListPaginatorContext()), context)
コード例 #9
0
def question_list(request, initial,
                  list_description=_('questions'),
                  base_path=None,
                  page_title=_("All Questions"),
                  allowIgnoreTags=True,
                  feed_url=None,
                  paginator_context=None,
                  show_summary=None,
                  feed_sort=('-added_at',),
                  feed_req_params_exclude=(_('page'), _('pagesize'), _('sort')),
                  extra_context={}):

    if show_summary is None:
        show_summary = bool(settings.SHOW_SUMMARY_ON_QUESTIONS_LIST)

    questions = initial.filter_state(deleted=False)

    if request.user.is_authenticated() and allowIgnoreTags:
        questions = questions.filter(~Q(tags__id__in = request.user.marked_tags.filter(user_selections__reason = 'bad')))

    if page_title is None:
        page_title = _("Questions")

    if request.GET.get('type', None) == 'rss':
        if feed_sort:
            questions = questions.order_by(*feed_sort)
        return RssQuestionFeed(request, questions, page_title, list_description)(request)

    keywords =  ""
    if request.GET.get("q"):
        keywords = request.GET.get("q").strip()

    #answer_count = Answer.objects.filter_state(deleted=False).filter(parent__in=questions).count()
    #answer_description = _("answers")

    if not feed_url:
        req_params = generate_uri(request.GET, feed_req_params_exclude)

        if req_params:
            req_params = '&' + req_params

        feed_url = request.path + "?type=rss" + req_params

    context = {
        'questions' : questions.distinct(),
        'questions_count' : questions.count(),
        'keywords' : keywords,
        'list_description': list_description,
        'base_path' : base_path,
        'page_title' : page_title,
        'tab' : 'questions',
        'feed_url': feed_url,
        'show_summary' : show_summary,
    }
    context.update(extra_context)

    return pagination.paginated(request,
                               ('questions', paginator_context or QuestionListPaginatorContext()), context)
コード例 #10
0
ファイル: readers.py プロジェクト: p2pu/osqa-badges
def question(request, id, slug='', answer=None):
    try:
        question = Question.objects.get(id=id)
    except:
        if slug:
            question = match_question_slug(id, slug)
            if question is not None:
                return HttpResponseRedirect(question.get_absolute_url())

        raise Http404()

    if question.nis.deleted and not request.user.can_view_deleted_post(question):
        raise Http404

    if request.GET.get('type', None) == 'rss':
        return RssAnswerFeed(request, question, include_comments=request.GET.get('comments', None) == 'yes')(request)

    if answer:
        answer = get_object_or_404(Answer, id=answer)

        if (question.nis.deleted and not request.user.can_view_deleted_post(question)) or answer.question != question:
            raise Http404

        if answer.marked:
            return HttpResponsePermanentRedirect(question.get_absolute_url())

        return answer_redirect(request, answer)

    if settings.FORCE_SINGLE_URL and (slug != slugify(question.title)):
        return HttpResponsePermanentRedirect(question.get_absolute_url())

    if request.POST:
        answer_form = AnswerForm(request.POST, user=request.user)
    else:
        answer_form = AnswerForm(user=request.user)

    answers = request.user.get_visible_answers(question)

    update_question_view_times(request, question)

    if request.user.is_authenticated():
        try:
            subscription = QuestionSubscription.objects.get(question=question, user=request.user)
        except:
            subscription = False
    else:
        subscription = False
    from forum.models import CustomBadge
    response_restricted = CustomBadge.is_response_restricted(request.user, question)

    return pagination.paginated(request, ('answers', AnswerPaginatorContext()), {
    "question" : question,
    "answer" : answer_form,
    "answers" : answers,
    "similar_questions" : question.get_related_questions(),
    "subscription": subscription,
    'response_restricted': response_restricted,
    })
コード例 #11
0
def user_preferences(request, user, **kwargs):
    questions = Question.objects.filter_state(deleted=False).filter(
        author=user).order_by('-added_at')
    answers = Answer.objects.filter_state(deleted=False).filter(
        author=user).order_by('-added_at')

    # Check whether the passed slug matches the one for the user object
    slug = kwargs['slug']
    if slug != slugify(smart_unicode(user.username)):
        return HttpResponseRedirect(user.get_absolute_url())

    up_votes = user.vote_up_count
    down_votes = user.vote_down_count
    votes_today = user.get_vote_count_today()
    votes_total = user.can_vote_count_today()

    user_tags = Tag.objects.filter(Q(nodes__author=user) | Q(nodes__children__author=user)) \
        .annotate(user_tag_usage_count=Count('name')).order_by('-user_tag_usage_count')

    awards = [
        (Badge.objects.get(id=b['id']), b['count'])
        for b in Badge.objects.filter(awards__user=user).values('id').annotate(
            count=Count('cls')).order_by('-count')
    ]

    # for the reputation history
    rep = list(user.reputes.order_by('date'))
    values = [r.value for r in rep]
    redux = lambda x, y: x + y

    graph_data = json.dumps([(time.mktime(rep[i].date.timetuple()) * 1000,
                              reduce(redux, values[:i + 1], 0))
                             for i in range(len(values))])

    rep = user.reputes.filter(action__canceled=False).order_by('-date')[0:20]

    return pagination.paginated(
        request,
        (('questions',
          QuestionListPaginatorContext(
              'USER_QUESTION_LIST', _('questions'), default_pagesize=15)),
         ('answers', UserAnswersPaginatorContext())), {
             "view_user": user,
             "questions": questions,
             "answers": answers,
             "up_votes": up_votes,
             "down_votes": down_votes,
             "total_votes": up_votes + down_votes,
             "votes_today_left": votes_total - votes_today,
             "votes_total_per_day": votes_total,
             "user_tags": user_tags[:50],
             "awards": awards,
             "total_awards": len(awards),
             "reputation": rep,
             "graph_data": graph_data,
         })
コード例 #12
0
def question(request, id, slug='', answer=None):
    try:
        question = Question.objects.get(id=id)
    except:
        if slug:
            question = match_question_slug(id, slug)
            if question is not None:
                return HttpResponseRedirect(question.get_absolute_url())

        raise Http404()

    if question.nis.deleted and not request.user.can_view_deleted_post(question):
        raise Http404

    if request.GET.get('type', None) == 'rss':
        return RssAnswerFeed(request, question, include_comments=request.GET.get('comments', None) == 'yes')(request)

    if answer:
        answer = get_object_or_404(Answer, id=answer)

        if (question.nis.deleted and not request.user.can_view_deleted_post(question)) or answer.question != question:
            raise Http404

        if answer.marked:
            return HttpResponsePermanentRedirect(question.get_absolute_url())

        return answer_redirect(request, answer)

    if settings.FORCE_SINGLE_URL and (slug != slugify(question.title)):
        return HttpResponsePermanentRedirect(question.get_absolute_url())

    if request.POST:
        answer_form = AnswerForm(request.POST, user=request.user)
    else:
        answer_form = AnswerForm(user=request.user)

    answers = request.user.get_visible_answers(question)

    update_question_view_times(request, question)

    if request.user.is_authenticated():
        try:
            subscription = QuestionSubscription.objects.get(question=question, user=request.user)
        except:
            subscription = False
    else:
        subscription = False

    return pagination.paginated(request, ('answers', AnswerPaginatorContext()), {
    "question" : question,
    "answer" : answer_form,
    "answers" : answers,
    "similar_questions" : question.get_related_questions(),
    "subscription": subscription,
    })
コード例 #13
0
ファイル: users.py プロジェクト: sumeshcjacob/keralaentrance
def users(request):
    suser = request.REQUEST.get('q', "")
    users = User.objects.all()

    if suser != "":
        users = users.filter(username__icontains=suser)

    return pagination.paginated(request, ('users', UserListPaginatorContext()), {
        "users" : users,
        "suser" : suser,
    })
コード例 #14
0
def online_users(request):
    suser = request.REQUEST.get('q', "")

    one_hour_ago = datetime.datetime.now() - datetime.timedelta(hours=1)
    sql_datetime = datetime.datetime.strftime(one_hour_ago, '%Y-%m-%d %H:%M:%S')
    users = User.objects.order_by('-last_seen')

    return pagination.paginated(request, ('users', UserListPaginatorContext()), {
        "users" : users,
        "suser" : suser,
    })
コード例 #15
0
ファイル: users.py プロジェクト: teknolab/teknolab-osqa
def user_subscriptions(request, user):
    enabled = user.subscription_settings.enable_notifications

    tab = request.GET.get('tab', "settings")

    if tab == 'settings':
        manage_open = False
        if request.method == 'POST':
            manage_open = False
            form = SubscriptionSettingsForm(data=request.POST, instance=user.subscription_settings)

            if form.is_valid():
                form.save()
                message = _('New subscription settings are now saved')

                if 'notswitch' in request.POST:
                    enabled = not enabled

                    if enabled:
                        message = _('Notifications are now enabled')
                    else:
                        message = _('Notifications are now disabled')

                user.subscription_settings.enable_notifications = enabled
                user.subscription_settings.save()

                request.user.message_set.create(message=message)
        else:
            form = SubscriptionSettingsForm(instance=user.subscription_settings)

        return {
            'view_user':user,
            'notificatons_on': enabled,
            'form':form,
            'manage_open':manage_open,
        }

    elif tab == 'manage':
        manage_open = True

        auto = request.GET.get('auto', 'True')
        if auto == 'True':
            show_auto = True
            subscriptions = QuestionSubscription.objects.filter(user=user).order_by('-last_view')
        else:
            show_auto = False
            subscriptions = QuestionSubscription.objects.filter(user=user, auto_subscription=False).order_by('-last_view')

        return pagination.paginated(request, ('subscriptions', SubscriptionListPaginatorContext()), {
            'subscriptions':subscriptions,
            'view_user':user,
            "auto":show_auto,
            'manage_open':manage_open,
        })
コード例 #16
0
ファイル: users.py プロジェクト: teknolab/teknolab-osqa
def users(request):
    suser = request.REQUEST.get('q', "")
    users = User.objects.all()

    if suser != "":
        users = users.filter(username__icontains=suser)

    return pagination.paginated(request, ('users', UserListPaginatorContext()), {
        "users" : users,
        "suser" : suser,
    })
コード例 #17
0
ファイル: readers.py プロジェクト: nickpack/OSQA
def tags(request):
    stag = ""
    tags = Tag.active.all()

    if request.method == "GET":
        stag = request.GET.get("q", "").strip()
        if stag:
            tags = tags.filter(name__icontains=stag)

    return pagination.paginated(
        request, ("tags", TagPaginatorContext()), {"tags": tags, "stag": stag, "keywords": stag}
    )
コード例 #18
0
def question_list(request,
                  initial,
                  list_description=_('questions'),
                  base_path=None,
                  page_title=_("All Questions"),
                  allowIgnoreTags=True,
                  feed_url=None,
                  paginator_context=None,
                  isIndex=None):

    questions = initial.filter_state(deleted=False)

    if request.user.is_authenticated() and allowIgnoreTags:
        questions = questions.filter(~Q(
            tags__id__in=request.user.marked_tags.filter(
                user_selections__reason='bad')))

    if page_title is None:
        page_title = _("Questions")

    if request.GET.get('type', None) == 'rss':
        questions = questions.order_by('-added_at')
        return RssQuestionFeed(request, questions, page_title,
                               list_description)(request)

    keywords = ""
    if request.GET.get("q"):
        keywords = request.GET.get("q").strip()

    #answer_count = Answer.objects.filter_state(deleted=False).filter(parent__in=questions).count()
    #answer_description = _("answers")

    if not feed_url:
        req_params = generate_uri(request.GET,
                                  (_('page'), _('pagesize'), _('sort')))
        if req_params:
            req_params = '&' + req_params

        feed_url = request.path + "?type=rss" + req_params

    return pagination.paginated(
        request,
        ('questions', paginator_context or QuestionListPaginatorContext()), {
            "questions": questions.distinct(),
            "questions_count": questions.count(),
            "keywords": keywords,
            "list_description": list_description,
            "base_path": base_path,
            "page_title": page_title,
            "tab": "index" if isIndex else "questions",
            'feed_url': feed_url,
        })
コード例 #19
0
ファイル: users.py プロジェクト: m10n/bestofever
def _user_subscriptions(request, user, **kwargs):
    enabled = True

    tab = request.GET.get('tab', "settings")

    # Manage tab
    if tab == 'manage':
        manage_open = True

        auto = request.GET.get('auto', 'True')
        if auto == 'True':
            show_auto = True
            subscriptions = QuestionSubscription.objects.filter(
                user=user).order_by('-last_view')
        else:
            show_auto = False
            subscriptions = QuestionSubscription.objects.filter(
                user=user, auto_subscription=False).order_by('-last_view')

        return pagination.paginated(
            request, ('subscriptions', SubscriptionListPaginatorContext()), {
                'subscriptions': subscriptions,
                'view_user': user,
                "auto": show_auto,
                'manage_open': manage_open,
            })
    # Settings Tab and everything else
    else:
        manage_open = False
        if request.method == 'POST':
            manage_open = False
            form = SubscriptionSettingsForm(
                data=request.POST, instance=user.subscription_settings)

            if form.is_valid():
                form.save()
                message = _('New subscription settings are now saved')

                user.subscription_settings.enable_notifications = enabled
                user.subscription_settings.save()

                messages.info(request, message)
        else:
            form = SubscriptionSettingsForm(
                instance=user.subscription_settings)

        return {
            'view_user': user,
            'notificatons_on': enabled,
            'form': form,
            'manage_open': manage_open,
        }
コード例 #20
0
ファイル: meta.py プロジェクト: jledbetter/osqa-badges
def badges(request):
    CustomBadge.load_custom_badges()
    badges = Badge.objects.all()

    if request.user.is_authenticated():
        my_badges = Award.objects.filter(user=request.user).values('badge_id').distinct()
    else:
        my_badges = []

    return pagination.paginated(request, ('badges', BadgesPaginatorContext()), {
        'badges' : badges,
        'mybadges' : my_badges,
    })
コード例 #21
0
ファイル: admin.py プロジェクト: podpora/podpora
def dashboard(request):
    return (
        "podporaadmin/dashboard.html",
        pagination.paginated(
            request,
            ("recent_activity", ActivityPaginatorContext()),
            {
                "settings_pack": unicode(settings.SETTINGS_PACK),
                "statistics": get_statistics(),
                "recent_activity": get_recent_activity(),
                "flagged_posts": get_flagged_posts(),
            },
        ),
    )
コード例 #22
0
def tags(request):
    stag = ""
    tags = Tag.active.all()

    if request.method == "GET":
        stag = request.GET.get("q", "").strip()
        if stag:
            tags = tags.filter(name__icontains=stag)

    return pagination.paginated(request, ('tags', TagPaginatorContext()), {
        "tags" : tags,
        "stag" : stag,
        "keywords" : stag
    })
コード例 #23
0
ファイル: readers.py プロジェクト: vjpr/poliwatch-osqa
def politicians(request):
    spoli = ""
    politicians = Politician.objects.all()

    if request.method == "GET":
        spoli = request.GET.get("q", "").strip()
        if spoli:
            politicians = politicians.filter(name__contains=spoli)

    return pagination.paginated(request, ('politicians', PoliticianPaginatorContext()), {
        "politicians" : politicians,
        "spoli" : spoli,
        "keywords" : spoli
    })
コード例 #24
0
ファイル: readers.py プロジェクト: dal-bhaat/stack5
def question_list(request, initial,
                  list_description=_('questions'),
                  base_path=None,
                  page_title=_("All Questions"),
                  allowIgnoreTags=True,
                  feed_url=None,
                  paginator_context=None,
                  is_home_page=False,
                  tag = None,
                  known_tip = None):

    questions = initial.filter_state(deleted=False)

    if request.user.is_authenticated() and allowIgnoreTags:
        questions = questions.filter(~Q(tags__id__in = request.user.marked_tags.filter(user_selections__reason = 'bad')))

    if page_title is None:
        page_title = _("Questions")

    if request.GET.get('type', None) == 'rss':
        questions = questions.order_by('-added_at')
        return RssQuestionFeed(request, questions, page_title, list_description)(request)

    keywords =  ""
    if request.GET.get("q"):
        keywords = request.GET.get("q").strip()

    #answer_count = Answer.objects.filter_state(deleted=False).filter(parent__in=questions).count()
    #answer_description = _("answers")

    if not feed_url:
        req_params = "&".join(generate_uri(request.GET, (_('page'), _('pagesize'), _('sort'))))
        if req_params:
            req_params = '&' + req_params

        feed_url = mark_safe(escape(request.path + "?type=rss" + req_params))

    return pagination.paginated(request, ('questions', paginator_context or QuestionListPaginatorContext()), {
    "questions" : questions.distinct(),
    "questions_count" : len(questions),
    "keywords" : keywords,
    "list_description": list_description,
    "base_path" : base_path,
    "page_title" : page_title,
    "tab" : "questions",
    'feed_url': feed_url,
    'is_home_page' : is_home_page,
    'tag' : tag,
    'known_tip' : known_tip,
    })
コード例 #25
0
ファイル: users.py プロジェクト: Alejoss/osqa
def _user_subscriptions(request, user, **kwargs):
    enabled = True

    tab = request.GET.get('tab', "settings")

    # Manage tab
    if tab == 'manage':
        manage_open = True

        auto = request.GET.get('auto', 'True')
        if auto == 'True':
            show_auto = True
            subscriptions = QuestionSubscription.objects.filter(user=user).order_by('-last_view')
        else:
            show_auto = False
            subscriptions = QuestionSubscription.objects.filter(user=user, auto_subscription=False).order_by('-last_view')

        return pagination.paginated(request, ('subscriptions', SubscriptionListPaginatorContext()), {
            'subscriptions':subscriptions,
            'view_user':user,
            "auto":show_auto,
            'manage_open':manage_open,
        })
    # Settings Tab and everything else
    else:
        manage_open = False
        if request.method == 'POST':
            manage_open = False
            form = SubscriptionSettingsForm(data=request.POST, instance=user.subscription_settings)

            if form.is_valid():
                form.save()
                message = _('New subscription settings are now saved')

                user.subscription_settings.enable_notifications = enabled
                user.subscription_settings.save()

                messages.info(request, message)
        else:
            form = SubscriptionSettingsForm(instance=user.subscription_settings)

        return {
            'view_user':user,
            'notificatons_on': enabled,
            'form':form,
            'manage_open':manage_open,
        }
コード例 #26
0
def node_management(request):
    if request.POST:
        params = pagination.generate_uri(request.GET, ('page',))

        if "save_filter" in request.POST:
            filter_name = request.POST.get('filter_name', _('filter'))
            params = pagination.generate_uri(request.GET, ('page',))
            current_filters = settings.NODE_MAN_FILTERS.value
            current_filters.append((filter_name, params))
            settings.NODE_MAN_FILTERS.set_value(current_filters)

        elif r"execute" in request.POST:
            selected_nodes = request.POST.getlist('_selected_node')

            if selected_nodes and request.POST.get('action', None):
                action = request.POST['action']
                selected_nodes = Node.objects.filter(id__in=selected_nodes)

                message = _("No action performed")

                if action == 'delete_selected':
                    for node in selected_nodes:
                        if node.node_type in ('question', 'answer', 'comment') and (not node.nis.deleted):
                            DeleteAction(user=request.user, node=node, ip=request.META['REMOTE_ADDR']).save()

                    message = _("All selected nodes marked as deleted")

                if action == 'undelete_selected':
                    for node in selected_nodes:
                        if node.node_type in ('question', 'answer', 'comment') and (node.nis.deleted):
                            node.nstate.deleted.cancel(ip=request.META['REMOTE_ADDR'])

                    message = _("All selected nodes undeleted")

                if action == "close_selected":
                    for node in selected_nodes:
                        if node.node_type == "question" and (not node.nis.closed):
                            CloseAction(node=node.leaf, user=request.user, extra=_("bulk close"), ip=request.META['REMOTE_ADDR']).save()

                    message = _("Selected questions were closed")

                if action == "hard_delete_selected":
                    ids = [n.id for n in selected_nodes]

                    for id in ids:
                        try:
                            node = Node.objects.get(id=id)
                            node.delete()
                        except:
                            pass

                    message = _("All selected nodes deleted")

                request.user.message_set.create(message=message)

                params = pagination.generate_uri(request.GET, ('page',))
                
            return HttpResponseRedirect(reverse("admin_tools", kwargs={'name': 'nodeman'}) + "?" + params)


    nodes = Node.objects.all()

    text = request.GET.get('text', '')
    text_in = request.GET.get('text_in', 'body')

    authors = request.GET.getlist('authors')
    tags = request.GET.getlist('tags')

    type_filter = request.GET.getlist('node_type')
    state_filter = request.GET.getlist('state_type')
    state_filter_type = request.GET.get('state_filter_type', 'any')

    if type_filter:
        nodes = nodes.filter(node_type__in=type_filter)

    state_types = NodeState.objects.filter(node__in=nodes).values_list('state_type', flat=True).distinct('state_type')
    state_filter = [s for s in state_filter if s in state_types]

    if state_filter:
        if state_filter_type == 'all':
            nodes = nodes.all_states(*state_filter)
        else:
            nodes = nodes.any_state(*state_filter)

    if (authors):
        nodes = nodes.filter(author__id__in=authors)
        authors = User.objects.filter(id__in=authors)

    if (tags):
        nodes = nodes.filter(tags__id__in=tags)
        tags = Tag.objects.filter(id__in=tags)

    if text:
        text_in = request.GET.get('text_in', 'body')
        filter = None

        if text_in == 'title' or text_in == 'both':
            filter = models.Q(title__icontains=text)

        if text_in == 'body' or text_in == 'both':
            sec_filter = models.Q(body__icontains=text)
            if filter:
                filter = filter | sec_filter
            else:
                filter = sec_filter

        if filter:
            nodes = nodes.filter(filter)

    node_types = [(k, n.friendly_name) for k, n in NodeMetaClass.types.items()]

    return ('osqaadmin/nodeman.html', pagination.paginated(request, ("nodes", NodeManagementPaginatorContext()), {
    'nodes': nodes,
    'text': text,
    'text_in': text_in,
    'type_filter': type_filter,
    'state_filter': state_filter,
    'state_filter_type': state_filter_type,
    'node_types': node_types,
    'state_types': state_types,
    'authors': authors,
    'tags': tags,
    'hide_menu': True
    }))
コード例 #27
0
ファイル: readers.py プロジェクト: viikasgarg/osqa
def categories(request):
    categories = OsqaCategory.objects.exclude(id = 5)         ## hiding system Authentication category
    return pagination.paginated(request, ('categories', CategoryPaginatorContext()), {
        "categories" : categories,
    })
コード例 #28
0
ファイル: admin.py プロジェクト: podpora/podpora
def node_management(request):
    if request.POST:
        params = pagination.generate_uri(request.GET, ("page",))

        if "save_filter" in request.POST:
            filter_name = request.POST.get("filter_name", _("filter"))
            params = pagination.generate_uri(request.GET, ("page",))
            current_filters = settings.NODE_MAN_FILTERS.value
            current_filters.append((filter_name, params))
            settings.NODE_MAN_FILTERS.set_value(current_filters)

        elif r"execute" in request.POST:
            selected_nodes = request.POST.getlist("_selected_node")

            if selected_nodes and request.POST.get("action", None):
                action = str(request.POST["action"])
                selected_nodes = Node.objects.filter(id__in=selected_nodes)

                message = _("No action performed")

                if action == "delete_selected":
                    for node in selected_nodes:
                        if node.node_type in ("question", "answer", "comment") and (not node.nis.deleted):
                            DeleteAction(user=request.user, node=node, ip=request.META["REMOTE_ADDR"]).save()

                    message = _("All selected nodes marked as deleted")

                if action == "undelete_selected":
                    for node in selected_nodes:
                        if node.node_type in ("question", "answer", "comment") and (node.nis.deleted):
                            node.nstate.deleted.cancel(ip=request.META["REMOTE_ADDR"])

                    message = _("All selected nodes undeleted")

                if action == "close_selected":
                    for node in selected_nodes:
                        if node.node_type == "question" and (not node.nis.closed):
                            CloseAction(
                                node=node.leaf, user=request.user, extra=_("bulk close"), ip=request.META["REMOTE_ADDR"]
                            ).save()

                    message = _("Selected questions were closed")

                if action == "hard_delete_selected":
                    ids = [n.id for n in selected_nodes]

                    for id in ids:
                        try:
                            node = Node.objects.get(id=id)
                            node.delete()
                        except:
                            pass

                    message = _("All selected nodes deleted")

                request.user.message_set.create(message=message)

                params = pagination.generate_uri(request.GET, ("page",))

            return HttpResponseRedirect(reverse("admin_tools", kwargs={"name": "nodeman"}) + "?" + params)

    nodes = Node.objects.all()

    text = request.GET.get("text", "")
    text_in = request.GET.get("text_in", "body")

    authors = request.GET.getlist("authors")
    tags = request.GET.getlist("tags")

    type_filter = request.GET.getlist("node_type")
    state_filter = request.GET.getlist("state_type")
    state_filter_type = request.GET.get("state_filter_type", "any")

    if type_filter:
        nodes = nodes.filter(node_type__in=type_filter)

    state_types = NodeState.objects.filter(node__in=nodes).values_list("state_type", flat=True).distinct("state_type")
    state_filter = [s for s in state_filter if s in state_types]

    if state_filter:
        if state_filter_type == "all":
            nodes = nodes.all_states(*state_filter)
        else:
            nodes = nodes.any_state(*state_filter)

    if authors:
        nodes = nodes.filter(author__id__in=authors)
        authors = User.objects.filter(id__in=authors)

    if tags:
        nodes = nodes.filter(tags__id__in=tags)
        tags = Tag.objects.filter(id__in=tags)

    if text:
        text_in = request.GET.get("text_in", "body")
        filter = None

        if text_in == "title" or text_in == "both":
            filter = models.Q(title__icontains=text)

        if text_in == "body" or text_in == "both":
            sec_filter = models.Q(body__icontains=text)
            if filter:
                filter = filter | sec_filter
            else:
                filter = sec_filter

        if filter:
            nodes = nodes.filter(filter)

    node_types = [(k, n.friendly_name) for k, n in NodeMetaClass.types.items()]

    return (
        "podporaadmin/nodeman.html",
        pagination.paginated(
            request,
            ("nodes", NodeManagementPaginatorContext()),
            {
                "nodes": nodes,
                "text": text,
                "text_in": text_in,
                "type_filter": type_filter,
                "state_filter": state_filter,
                "state_filter_type": state_filter_type,
                "node_types": node_types,
                "state_types": state_types,
                "authors": authors,
                "tags": tags,
                "hide_navigation": True,
            },
        ),
    )
コード例 #29
0
ファイル: meta.py プロジェクト: jledbetter/osqa-badges
def badge(request, id, slug):
    badge = Badge.objects.get(id=id)
    award_queryset = Award.objects.filter(badge=badge)
    awards = list(award_queryset.order_by('user', 'awarded_at'))
    award_count = len(awards)

    awards = sorted([dict(count=len(list(g)), user=k) for k, g in groupby(awards, lambda a: a.user)],
                    lambda c1, c2: c2['count'] - c1['count'])

    kwargs = {
        'award_count': award_count,
        'awards' : awards,
        'badge' : badge,
        'requires_submitted_work': False,
        'peer_given': False,
    }

    try:
        custom_badge = badge.custombadge_set.get()
        kwargs['long_description'] = custom_badge.long_description
        if custom_badge.is_peer_given:
            kwargs['is_peer_award_restricted'] = custom_badge.is_peer_award_restricted(request.user)
            if request.POST:
                kwargs['award_form'] = AwardBadgeForm(request.POST, user=request.user, custom_badge=custom_badge)
            else:
                kwargs['award_form'] = AwardBadgeForm(user=request.user, custom_badge=custom_badge)
            if request.method == "POST" and kwargs['award_form'].is_valid():
                award_comment = AwardComment(author=request.user, body=kwargs['award_form'].cleaned_data['text'])
                award_comment.save()
                class DummyAction:
                    node = award_comment
                award_badge(badge, kwargs['award_form'].cleaned_data['user'], DummyAction(), False)
                return HttpResponseRedirect(badge.get_absolute_url() + "#%s" % award_comment.id)
            kwargs['peer_given'] = True
            kwargs['award_comments'] = award_queryset
            if request.method == 'GET' and 'user_filter' in request.GET and request.GET['user_filter']:
                filter_form = BadgeFilterForm(request.GET)
                if filter_form.is_valid():
                    kwargs['user_filter'] = filter_form.cleaned_data['user_filter']
                    kwargs['award_comments'] = award_queryset.filter(user=kwargs['user_filter'])
            else:
                filter_form = BadgeFilterForm()
            kwargs['filter_form'] = filter_form
            kwargs = pagination.paginated(request,
                ('award_comments', BadgesAwardCommentsPaginatorContext()), kwargs)
        elif custom_badge.min_required_votes > 0:
            kwargs['requires_submitted_work'] = True
            kwargs['questions'] = Question.objects.filter_state(deleted=False).filter_tag(
                custom_badge.tag_name).order_by('-added_at')
            kwargs['answers'] = Answer.objects.filter_state(deleted=False).filter(
                parent__id__in=[q.id for q in kwargs['questions']]).order_by('-score')
            if request.method == 'GET' and 'user_filter' in request.GET and request.GET['user_filter']:
                filter_form = BadgeFilterForm(request.GET)
                if filter_form.is_valid():
                    kwargs['user_filter'] = filter_form.cleaned_data['user_filter']
                    kwargs['answers'] = kwargs['answers'].filter(author=kwargs['user_filter'])
            else:
                filter_form = BadgeFilterForm()
            kwargs['filter_form'] = filter_form
            kwargs = pagination.paginated(request, (
                ('questions', QuestionListPaginatorContext('USER_QUESTION_LIST', _('questions'), 3)),
                ('answers', BadgesAnswersPaginatorContext())), kwargs)
    except CustomBadge.DoesNotExist:
        pass

    return render_to_response('badge.html', kwargs,
        context_instance=RequestContext(request))
コード例 #30
0
ファイル: readers.py プロジェクト: dal-bhaat/stack5
def question(request, id, slug='', answer=None):
    try:
        question = Question.objects.get(id=id)

        question_headline = question.headline
        question_body = question.html
        tags = question.tags.all()

        if question.pendding_suggestion and question.pendding_suggestion.author == request.user:
            question_body = static_content(question.pendding_suggestion.body,"markdown")
            question_headline = question.pendding_suggestion.title
            tags = list(Tag.objects.filter(name__in=question.pendding_suggestion.tagname_list()))

    except:
        if slug:
            question = match_question_slug(id, slug)
            if question is not None:
                return HttpResponseRedirect(question.get_absolute_url())

        raise Http404()

    if question.nis.deleted and not request.user.can_view_deleted_post(question):
        raise Http404

    if request.GET.get('type', None) == 'rss':
        return RssAnswerFeed(request, question, include_comments=request.GET.get('comments', None) == 'yes')(request)

    if answer:
        answer = get_object_or_404(Answer, id=answer)

        if (question.nis.deleted and not request.user.can_view_deleted_post(question)) or answer.question != question:
            raise Http404

        if answer.marked:
            return HttpResponsePermanentRedirect(question.get_absolute_url())

        return answer_redirect(request, answer)

    if settings.FORCE_SINGLE_URL and (slug != slugify(question.title)):
        return HttpResponsePermanentRedirect(question.get_absolute_url())

    if request.POST:
        answer_form = AnswerForm(request.POST, user=request.user)
    else:
        answer_form = AnswerForm(user=request.user)

    answers = request.user.get_visible_answers(question)

    update_question_view_times(request, question)

    if request.user.is_authenticated():
        try:
            subscription = QuestionSubscription.objects.get(question=question, user=request.user)
        except:
            subscription = False
    else:
        subscription = False

    return pagination.paginated(request, ('answers', AnswerPaginatorContext()), {
    "question" : question,
    "question_headline" : question_headline,    
    "question_body" : question_body,
    "tags" : tags,
    "answer" : answer_form,
    "answers" : answers,
    "similar_questions" : question.get_related_questions(),
    "subscription": subscription,
    })
コード例 #31
0
ファイル: views.py プロジェクト: jwmonroe/Magnate-Application
class DashboardPaginatorContext(pagination.PaginatorContext):
    def __init__(self):
        super(DashboardPaginatorContext,
              self).__init__('DASHBOARD_FEED',
                             pagesizes=(5, 10, 20, 50, 100),
                             default_pagesize=100)


# Weird hack to disable pagination for unit tests.
# This is because pagination relies on OSQA's extended user, which
# relies on custom middleware, but unit tests do not run custom middleware,
# so everything fails.
from django.conf import settings
if not settings.TESTING:
    f_render = lambda request, ctx: pagination.paginated(
        request, ("entries", DashboardPaginatorContext()), ctx)
else:

    def f(request, ctx):
        entries = ctx['entries']
        ctx['entries'] = {
            'paginator': {
                'page': entries
            }
        }  # fake entries.paginator.page
        return ctx

    f_render = f


# those go to the top of the feed
コード例 #32
0
ファイル: readers.py プロジェクト: softbalajibi/osqa
        try:
            subscription = QuestionSubscription.objects.get(question=question, user=request.user)
        except:
            subscription = False
    else:
        subscription = False
    try:
        focused_answer_id = int(request.GET.get("focusedAnswerId", None))
    except TypeError, ValueError:
        focused_answer_id = None

    return pagination.paginated(request, ('answers', AnswerPaginatorContext()), {
    "question" : question,
    "form" : answer_form,
    "answers" : answers,
    "similar_questions" : question.get_related_questions(),
    "subscription": subscription,
    "embed_youtube_videos" : settings.EMBED_YOUTUBE_VIDEOS,
    "focused_answer_id" : focused_answer_id
    })


REVISION_TEMPLATE = template.loader.get_template('node/revision.html')

def revisions(request, id):
    post = get_object_or_404(Node, id=id).leaf
    revisions = list(post.revisions.order_by('revised_at'))
    rev_ctx = []

    for i, revision in enumerate(revisions):
        rev_ctx.append(dict(inst=revision, html=template.loader.get_template('node/revision.html').render(template.Context({
コード例 #33
0
def question_list(request,
                  initial,
                  list_description=_('questions'),
                  base_path=None,
                  page_title=_("All Questions"),
                  allowIgnoreTags=True,
                  feed_url=None,
                  paginator_context=None,
                  show_summary=None,
                  feed_sort=('-added_at', ),
                  feed_req_params_exclude=(_('page'), _('pagesize'),
                                           _('sort')),
                  extra_context={}):

    if show_summary is None:
        show_summary = bool(settings.SHOW_SUMMARY_ON_QUESTIONS_LIST)

    questions = initial.filter_state(deleted=False)

    if request.user.is_authenticated() and allowIgnoreTags:
        questions = questions.filter(~Q(
            tags__id__in=request.user.marked_tags.filter(
                user_selections__reason='bad')))

    if page_title is None:
        page_title = _("Questions")

    # Added custom code to OSQA to make it more useful for Magnate
    # Only show those questions that are linked to a given Zinnia entry
    # BEGIN
    if request.GET.get('entry', None):
        from zinnia.models.entry import Entry
        try:
            entry_pk = int(request.GET.get('entry'))
            entry = Entry.objects.get(pk=entry_pk)  # make sure it exists
            if entry.is_public():
                questions = questions.filter(about_entries__entry__pk=entry_pk)
                page_title = _(unicode(page_title) + " about " + entry.title)
        except (ValueError, Entry.DoesNotExist) as e:
            # If the entry id is not integer, ignore ?entry
            # If there is no such entry, ignore ?entry
            # If there is, but it is not public, ignore ?entry
            # If it is public, show related entries and change the title
            pass
    # END

    if request.GET.get('type', None) == 'rss':
        if feed_sort:
            questions = questions.order_by(*feed_sort)
        return RssQuestionFeed(request, questions, page_title,
                               list_description)(request)

    keywords = ""
    if request.GET.get("q"):
        keywords = request.GET.get("q").strip()

    #answer_count = Answer.objects.filter_state(deleted=False).filter(parent__in=questions).count()
    #answer_description = _("answers")

    if not feed_url:
        req_params = generate_uri(request.GET, feed_req_params_exclude)

        if req_params:
            req_params = '&' + req_params

        feed_url = request.path + "?type=rss" + req_params

    context = {
        'questions': questions.distinct(),
        'questions_count': questions.count(),
        'keywords': keywords,
        'list_description': list_description,
        'base_path': base_path,
        'page_title': page_title,
        'tab': 'questions',
        'feed_url': feed_url,
        'show_summary': show_summary,
    }
    context.update(extra_context)

    return pagination.paginated(
        request,
        ('questions', paginator_context or QuestionListPaginatorContext()),
        context)
コード例 #34
0
ファイル: readers.py プロジェクト: perryhau/iCQA
def question(request, id, slug='', answer=None):
    try:
        question = Question.objects.get(id=id)
    except:
        if slug:
            question = match_question_slug(id, slug)
            if question is not None:
                return HttpResponseRedirect(question.get_absolute_url())

        raise Http404()

    if question.nis.deleted and not request.user.can_view_deleted_post(question):
        raise Http404

    if request.GET.get('type', None) == 'rss':
        return RssAnswerFeed(request, question, include_comments=request.GET.get('comments', None) == 'yes')(request)

    if answer:
        answer = get_object_or_404(Answer, id=answer)

        if (question.nis.deleted and not request.user.can_view_deleted_post(question)) or answer.question != question:
            raise Http404

        if answer.marked:
            return HttpResponsePermanentRedirect(question.get_absolute_url())

        return answer_redirect(request, answer)

    if settings.FORCE_SINGLE_URL and (slug != slugify(question.title)):
        return HttpResponsePermanentRedirect(question.get_absolute_url())

    if request.POST:
        answer_form = AnswerForm(request.POST, user=request.user)
    else:
        answer_form = AnswerForm(user=request.user)

    answers = request.user.get_visible_answers(question)

    update_question_view_times(request, question)

    if request.user.is_authenticated():
        try:
            subscription = QuestionSubscription.objects.get(question=question, user=request.user)
        except:
            subscription = False
    else:
        subscription = False

    from django.db import connection, transaction
    cursor = connection.cursor()
    cursor.execute("SELECT a.user_id, a.score FROM analytics_answerer_recommendation a WHERE a.question_id=%s AND NOT EXISTS (SELECT * FROM forum_node f WHERE f.id=a.question_id AND f.author_id=a.user_id) AND NOT EXISTS (SELECT * FROM forum_node f2 WHERE f2.parent_id=a.question_id AND f2.author_id=a.user_id) AND NOT EXISTS (SELECT * FROM forum_node f3 WHERE f3.parent_id=a.question_id AND f3.marked=1) ORDER BY score ASC LIMIT 12", [question.id])
    row_list = cursor.fetchall()
    user_list = []

    for row in row_list:
        user = User.objects.get(pk=row[0])
        if (row[1] > 0):
            user_list.append({"user": user, "score": row[1]})

    return pagination.paginated(request, ('answers', AnswerPaginatorContext()), {
    "question" : question,
    "answer" : answer_form,
    "answers" : answers,
    "similar_questions" : question.get_related_questions(),
    "subscription": subscription,
    "recommendedanswerers": user_list,
    })
コード例 #35
0
ファイル: readers.py プロジェクト: viikasgarg/osqa
    '''
    recipients_bycategory = []
    try:
        _recipients = [recipient.strip()  for recipient in OsqaCategory.objects.get(id = question.category).mail_recipients.split(',')]
        recipients_bycategory = [user for user in User.objects.filter(id__in = _recipients).distinct()]
    except:
        pass  ## not able to find category recipinets
    '''

    return pagination.paginated(request, ('answers', AnswerPaginatorContext()), {
    "question" : question,
    "answer" : answer_form,
    "attachment" : attachments,
    "answers" : answers,
    "similar_questions" : question.get_related_questions(),
    "subscription": subscription,
    "embed_youtube_videos" : settings.EMBED_YOUTUBE_VIDEOS,
    "focused_answer_id" : focused_answer_id,
    #"recipients" : question.recipientname_list(),
    #"recipients_bycategory":recipients_bycategory,
    "category_name": question.category_name(),
#    "addressbook_list":question.addressbook_list(),
    })


REVISION_TEMPLATE = template.loader.get_template('node/revision.html')

def get_attachment_file_as_httpresponse(request,id=None):
    """
    Send a file through Django without loading the whole file into
    memory at once. The FileWrapper will turn the file object into an
    iterator for chunks of 8KB.
コード例 #36
0
            subscription = QuestionSubscription.objects.get(question=question,
                                                            user=request.user)
        except:
            subscription = False
    else:
        subscription = False
    try:
        focused_answer_id = int(request.GET.get("focusedAnswerId", None))
    except TypeError, ValueError:
        focused_answer_id = None

    return pagination.paginated(
        request, ('answers', AnswerPaginatorContext()), {
            "question": question,
            "answer": answer_form,
            "answers": answers,
            "similar_questions": question.get_related_questions(),
            "subscription": subscription,
            "embed_youtube_videos": settings.EMBED_YOUTUBE_VIDEOS,
            "focused_answer_id": focused_answer_id
        })


REVISION_TEMPLATE = template.loader.get_template('node/revision.html')


def revisions(request, id):
    post = get_object_or_404(Node, id=id).leaf
    revisions = list(post.revisions.order_by('revised_at'))
    rev_ctx = []

    for i, revision in enumerate(revisions):
コード例 #37
0
ファイル: readers.py プロジェクト: suhailv/keralaentrance
        try:
            subscription = QuestionSubscription.objects.get(question=question, user=request.user)
        except:
            subscription = False
    else:
        subscription = False
    try:
        focused_answer_id = int(request.GET.get("focusedAnswerId", None))
    except TypeError, ValueError:
        focused_answer_id = None

    return pagination.paginated(request, ('answers', AnswerPaginatorContext()), {
    "question" : question,
    "answer" : answer_form,
    "answers" : answers,
    "similar_questions" : question.get_related_questions(),
    "subscription": subscription,
    "embed_youtube_videos" : settings.EMBED_YOUTUBE_VIDEOS,
    "focused_answer_id" : focused_answer_id,
    "correctopt":OptCorrect.objects.filter(question=question.id),
    })


REVISION_TEMPLATE = template.loader.get_template('node/revision.html')

def revisions(request, id):
    post = get_object_or_404(Node, id=id).leaf
    revisions = list(post.revisions.order_by('revised_at'))
    rev_ctx = []

    for i, revision in enumerate(revisions):
        rev_ctx.append(dict(inst=revision, html=template.loader.get_template('node/revision.html').render(template.Context({