Ejemplo n.º 1
0
def search(request):

    sqs = SearchQuerySet().models(Method)

    if request.GET.get('q'):

        form = SearchForm(request.GET, searchqueryset=sqs)

        if form.is_valid():
            query = form.cleaned_data['q']
            results = form.search()
            paginator = Paginator(results, 10)

            try:
                page = paginator.page(int(request.GET.get('page', 1)))
            except InvalidPage:
                raise Http404("No such page of results!")

    else:
        form = SearchForm(searchqueryset=sqs)
        paginator = None
        page = None
        query = request.GET.get('q')
    
    
    context = {
        'form': form,
        'page': page,
        'paginator': paginator,
        'query': query,
        'suggestion': None,
    }
    
    return render_to_response('search/method_search.html', context, context_instance=RequestContext(request))
Ejemplo n.º 2
0
def search(request):
    form = SearchForm(request.GET or None)
    posts = None
    if form.data != {} and form.is_valid():
        posts = form.search()
    return render_to_response('search/search.html', {
        'posts': posts
    }, context_instance=RequestContext(request))
Ejemplo n.º 3
0
    def test_unbound(self):
        sf = SearchForm({}, searchqueryset=self.sqs)

        self.assertEqual(sf.errors, {})
        self.assertEqual(sf.is_valid(), True)

        # This shouldn't blow up.
        sqs = sf.search()
        self.assertTrue(isinstance(sqs, EmptySearchQuerySet))
Ejemplo n.º 4
0
 def test_unbound(self):
     sf = SearchForm({}, searchqueryset=self.sqs)
     
     self.assertEqual(sf.errors, {})
     self.assertEqual(sf.is_valid(), True)
     
     # This shouldn't blow up.
     sqs = sf.search()
     self.assertTrue(isinstance(sqs, EmptySearchQuerySet))
Ejemplo n.º 5
0
def search(request):
    results = EmptySearchQuerySet()
    query = request.GET.get('q')
    if query:
        form = SearchForm(request.GET)
        if form.is_valid():
            results = form.search()
    else:
       form = SearchForm()
    return render(request, 'search/search.html', {'form':form, 'results':results, 'query':query})
Ejemplo n.º 6
0
 def get_queryset(self):
     query = ''
     results = []
     
     if self.request.QUERY_PARAMS.get('q'):
         # limit searchqueryset to appropriate model
         searchqueryset = SearchQuerySet().models(self.model)
         # then perform a search on specific model.
         form = SearchForm(self.request.QUERY_PARAMS, 
                           searchqueryset=searchqueryset, load_all=True)
         if form.is_valid():
             query = form.cleaned_data['q']
             results = form.search()
             results = self.filter_results(results)
             # for odd reasons there are duplicates in the haystack results.
             results = list_dedup([r.object for r in results])
     
     return results
Ejemplo n.º 7
0
def search_helper(request, searchqueryset, pagination_function):
    """
    Description: Helper function by searching
                 Based off haystack.views.basic_search()
                   
    Arguments:   - request:             HttpRequest object
                 - searchqueryset:      SearchQuerySet limited to a model by
                                        calling SearchQuerySet().models()
                 - pagination_function: Helper function for use in paginating
                                        the search results
    Return:      Dictionary with keys coming from pagination_function. Two
                 New keys will be added to it:
                 - query:      search query
                 - suggestion: backend-suggested search query
    
    Author:      Nnoduka Eruchalu
    """
    query = ''
    results = EmptySearchQuerySet()
    suggestion = False
    search_list = []

    if request.GET.get('q'):
        form = SearchForm(request.GET,
                          searchqueryset=searchqueryset,
                          load_all=True)
        if form.is_valid():
            query = form.cleaned_data['q']
            results = form.search()
            # for odd reasons there are duplicates in the haystack results...
            search_list = list_dedup([r.object for r in results])

        if results.query.backend.include_spelling:
            suggestion = form.get_suggestion()

    context = pagination_function(request, search_list)
    context['query'] = query
    context['suggestion'] = suggestion
    return context
Ejemplo n.º 8
0
def search_helper(request, searchqueryset, pagination_function):
    """
    Description: Helper function by searching
                 Based off haystack.views.basic_search()
                   
    Arguments:   - request:             HttpRequest object
                 - searchqueryset:      SearchQuerySet limited to a model by
                                        calling SearchQuerySet().models()
                 - pagination_function: Helper function for use in paginating
                                        the search results
    Return:      Dictionary with keys coming from pagination_function. Two
                 New keys will be added to it:
                 - query:      search query
                 - suggestion: backend-suggested search query
    
    Author:      Nnoduka Eruchalu
    """
    query = ''
    results = EmptySearchQuerySet()
    suggestion = False
    search_list = []
    
    if request.GET.get('q'):
        form = SearchForm(request.GET, searchqueryset=searchqueryset,
                          load_all=True)
        if form.is_valid():
            query = form.cleaned_data['q']
            results = form.search()
            # for odd reasons there are duplicates in the haystack results...
            search_list = list_dedup([r.object for r in results])
                                    
        if results.query.backend.include_spelling:
            suggestion = form.get_suggestion()
                        
    context = pagination_function(request, search_list)
    context['query'] = query
    context['suggestion'] = suggestion
    return context
Ejemplo n.º 9
0
def search(request):
    """ Returns messages corresponding to a query """
    mlist_fqdn = request.GET.get("mlist")
    if mlist_fqdn is None:
        mlist = None
    else:
        try:
            mlist = MailingList.objects.get(name=mlist_fqdn)
        except MailingList.DoesNotExist:
            raise Http404("No archived mailing-list by that name.")
        if not is_mlist_authorized(request, mlist):
            return render(request, "hyperkitty/errors/private.html", {
                            "mlist": mlist,
                          }, status=403)


    query = ''
    results = EmptySearchQuerySet()
    sqs = RelatedSearchQuerySet()

    # Remove private non-subscribed lists
    if mlist is not None:
        sqs = sqs.filter(mailinglist__exact=mlist.name)
    else:
        excluded_mlists = MailingList.objects.filter(
            archive_policy=ArchivePolicy.private.value)
        if request.user.is_authenticated():
            subscriptions = request.user.hyperkitty_profile.get_subscriptions()
            excluded_mlists = excluded_mlists.exclude(
                list_id__in=subscriptions.keys())
        excluded_mlists = excluded_mlists.values_list("name", flat=True)
        sqs = sqs.exclude(mailinglist__in=excluded_mlists)

    # Sorting
    sort_mode = request.GET.get('sort')
    if sort_mode == "date-asc":
        sqs = sqs.order_by("date")
    elif sort_mode == "date-desc":
        sqs = sqs.order_by("-date")

    # Handle data
    if request.GET.get('q'):
        form = SearchForm(
            request.GET, searchqueryset=sqs, load_all=True)
        if form.is_valid():
            query = form.cleaned_data['q']
            results = form.search()
    else:
        form = SearchForm(searchqueryset=sqs, load_all=True)

    emails = paginate(results, page_num=request.GET.get('page'))
    for email in emails:
        if request.user.is_authenticated():
            email.object.myvote = email.object.votes.filter(user=request.user).first()
        else:
            email.object.myvote = None


    context = {
        'mlist' : mlist,
        'form': form,
        'emails': emails,
        'query': query,
        'sort_mode': sort_mode,
        'suggestion': None,
    }
    if results.query.backend.include_spelling:
        context['suggestion'] = form.get_suggestion()

    return render(request, "hyperkitty/search_results.html", context)
Ejemplo n.º 10
0
def get_haystack_results(request):
    hs_form = SearchForm(request.GET)
    if hs_form.is_valid():
        return hs_form.search()
    return []
Ejemplo n.º 11
0
def search(request):
    """ Returns messages corresponding to a query """
    mlist_fqdn = request.GET.get("mlist")
    if mlist_fqdn is None:
        mlist = None
    else:
        try:
            mlist = MailingList.objects.get(name=mlist_fqdn)
        except MailingList.DoesNotExist:
            raise Http404("No archived mailing-list by that name.")
        if not is_mlist_authorized(request, mlist):
            return render(request,
                          "hyperkitty/errors/private.html", {
                              "mlist": mlist,
                          },
                          status=403)
    query = ''
    results = EmptySearchQuerySet()
    sqs = RelatedSearchQuerySet()

    # Remove private non-subscribed lists
    if mlist is not None:
        sqs = sqs.filter(mailinglist__exact=mlist.name)
    else:
        excluded_mlists = MailingList.objects.filter(
            archive_policy=ArchivePolicy.private.value)
        if request.user.is_authenticated:
            subscriptions = get_subscriptions(request.user)
            excluded_mlists = excluded_mlists.exclude(
                list_id__in=subscriptions.keys())
        excluded_mlists = excluded_mlists.values_list("name", flat=True)
        sqs = sqs.exclude(mailinglist__in=excluded_mlists)

    # Sorting
    sort_mode = request.GET.get('sort')
    if sort_mode == "date-asc":
        sqs = sqs.order_by("date")
    elif sort_mode == "date-desc":
        sqs = sqs.order_by("-date")

    # Handle data
    if request.GET.get('q'):
        form = SearchForm(request.GET, searchqueryset=sqs, load_all=True)
        if form.is_valid():
            query = form.cleaned_data['q']
            results = form.search()
    else:
        form = SearchForm(searchqueryset=sqs, load_all=True)

    try:
        emails = paginate(
            results,
            request.GET.get('page'),
            request.GET.get('count'),
        )
    except Exception as e:
        backend = settings.HAYSTACK_CONNECTIONS[DEFAULT_ALIAS]["ENGINE"]
        if backend == "haystack.backends.whoosh_backend.WhooshEngine":
            from whoosh.qparser.common import QueryParserError
            search_exception = QueryParserError
        if backend == "xapian_backend.XapianEngine":
            from xapian import QueryParserError
            search_exception = QueryParserError
        if not isinstance(e, search_exception):
            raise
        emails = paginate([])
        form.add_error(
            "q",
            ValidationError(
                _('Parsing error: %(error)s'),
                params={"error": e},
                code="parse",
            ))
    for email in emails:
        if request.user.is_authenticated:
            email.object.myvote = email.object.votes.filter(
                user=request.user).first()
        else:
            email.object.myvote = None

    context = {
        'mlist': mlist,
        'form': form,
        'emails': emails,
        'query': query,
        'sort_mode': sort_mode,
        'suggestion': None,
    }
    if results.query.backend.include_spelling:
        context['suggestion'] = form.get_suggestion()

    return render(request, "hyperkitty/search_results.html", context)
Ejemplo n.º 12
0
def images_search(request):
    """
    View to make search of images.

    :param request: Request to serve
    """

    query = ''
    time_start = ''
    time_end = ''
    post = request.POST
    enable_checkboxes = False

    if request.method == 'GET' and request.GET.get('q') is not None:
        request.method = 'POST'
        enable_checkboxes = True
        post = {'q': request.GET['q'],
                'time_start': request.GET.get('time_start', ''),
                'time_end': request.GET.get('time_end', '')}

    if request.method == 'POST':

        # Check if session have to be deleted
        if post.get('clear_form'):
            request.session.flush()
            pass

        # New search, clear data stored in session
        request.session['results_images'] = None
        form = SearchForm(post)
        restart = post.get('restart') is not None

        if form.is_valid():
            images = []
            categories_to_search = []
            query = form.cleaned_data['q'] if not restart else ''

            # Get categories to search and get left menu data
            for i in ImageCategory.objects.filter(visible_on_website=True):
                category_images = {}
                category_images["label_name"] = i.label
                category_images["label_code"] = i.value
                category_images["images"] = []
                search_set = SearchQuerySet().models(Image).filter(category_label__exact=i.label,
                                                                   ready_to_go=True).order_by('date')
                category_images["number_of_images"] = len(search_set)
                if restart or enable_checkboxes or post.get("checkbox" + str(i.value)):
                    categories_to_search.append(i.label)

                images.append(category_images)

            images = sorted(images, key=lambda k: k["label_name"])

            time_start = post.get('time_start') if not restart else ''
            time_end = post.get('time_end') if not restart else ''

            # Options if query is provided
            if query != "":
                if time_start != "" and time_end != "":
                    results = \
                        SearchQuerySet().filter(imgtext__icontains=query, ready_to_go=True,
                                                category_label__in=categories_to_search,
                                                date__gte=time_start,
                                                date__lte=time_end).models(Image).\
                            order_by('date')

                elif time_start != "":
                    results = \
                        SearchQuerySet().filter(imgtext__icontains=query, ready_to_go=True,
                                                category_label__in=categories_to_search,
                                                date__gte=time_start).models(Image).\
                            order_by('date')

                elif time_end != "":
                    results = \
                        SearchQuerySet().filter(imgtext__icontains=query, ready_to_go=True,
                                                category_label__in=categories_to_search,
                                                date__lte=time_end).models(Image).\
                            order_by('date')

                else:
                    results = \
                        SearchQuerySet().filter(imgtext__icontains=query, ready_to_go=True,
                                                category_label__in=categories_to_search).models(Image).\
                            order_by('date')

            elif time_start != "" or time_end != "":
                if time_start != "" and time_end != "":
                    results = \
                        SearchQuerySet().filter(ready_to_go=True,
                                                category_label__in=categories_to_search,
                                                date__gte=time_start,
                                                date__lte=time_end).models(Image).\
                            order_by('date')

                elif time_start != "":
                    results = \
                        SearchQuerySet().filter(ready_to_go=True,
                                                category_label__in=categories_to_search,
                                                date__gte=time_start).models(Image).\
                            order_by('date')

                elif time_end != "":
                    results = \
                        SearchQuerySet().filter(ready_to_go=True,
                                                category_label__in=categories_to_search,
                                                date__lte=time_end).models(Image).\
                            order_by('date')

                else:
                    if len(categories_to_search) == 1:
                        return HttpResponseRedirect(reverse('resources:images-category',
                                                        kwargs={'category': categories_to_search.pop()}))
                    else:
                        results = SearchQuerySet().all().filter(ready_to_go=True,
                                                            category_label__in=categories_to_search).\
                            order_by('date')

            else:
                if len(categories_to_search) > 1:
                    results = SearchQuerySet().all().filter(ready_to_go=True,
                                                            category_label__in=categories_to_search).\
                            order_by('date')
                else:
                    return HttpResponseRedirect(reverse('resources:images-category',
                                                        kwargs={'category': categories_to_search.pop()}))

        else:
            results = SearchQuerySet().model(Image).all()

        # Store results in session
        request.session['results_images'] = results
        request.session['images_images'] = images
        request.session['enabled_categories'] = categories_to_search
        request.session['query'] = query
        request.session['time_start'] = time_start
        request.session['time_end'] = time_end

    else:
        results = request.session.get('results_images')
        images = request.session.get('images_images')

    return render(request, 'resources/images-search-results.html',
            {'results': results,
             'images': images,
             'query': request.session['query'],
             'time_start': request.session['time_start'],
             'time_end': request.session['time_end'],
             'enabled_categories': request.session['enabled_categories']})
Ejemplo n.º 13
0
def search(request):
    """
    Description: Handles requests from site's search bar
                 Based off haystack.views.basic_search()
                   
    Arguments:   request: HttpRequest object
    Return:      HttpResponse object showing search results with following 
                 additional details
                 - query:      search query
                 - suggestion: backend-suggested search query
    
    Author:      Nnoduka Eruchalu
    """
    query = ""
    results = EmptySearchQuerySet()
    suggestion = False

    if request.GET.get("q"):
        form = SearchForm(request.GET, searchqueryset=None, load_all=True)
        if form.is_valid():
            query = form.cleaned_data["q"]
            results = form.search()

        if results.query.backend.include_spelling:
            suggestion = form.get_suggestion()

    search_list = [r.object for r in results]

    paginator = Paginator(search_list, settings.RESULTS_PER_PAGE)

    page = request.GET.get("page")
    try:
        results = paginator.page(page)
    except PageNotAnInteger:
        # if page is not an integer, deliver first page.
        results = paginator.page(1)
    except EmptyPage:
        # if page is out of range (e.g. 999), deliver last page of results
        results = paginator.page(paginator.num_pages)

    if results.has_next():
        next_page_num = results.next_page_number()
    else:
        next_page_num = 0  # way of indicating no more pages... 1 index'd helped!

    if results.has_previous():
        prev_page_num = results.previous_page_number()
    else:
        prev_page_num = 0

    results = results.object_list

    return render_to_response(
        "search/search.html",
        {
            "query": query,
            "suggestion": suggestion,
            "results": results,
            "next_page": next_page_num,
            "prev_page": prev_page_num,
        },
        context_instance=RequestContext(request),
    )
Ejemplo n.º 14
0
def search(request):
    """ Returns messages corresponding to a query """
    mlist_fqdn = request.GET.get("mlist")
    if mlist_fqdn is None:
        mlist = None
    else:
        try:
            mlist = MailingList.objects.get(name=mlist_fqdn)
        except MailingList.DoesNotExist:
            raise Http404("No archived mailing-list by that name.")
        if not is_mlist_authorized(request, mlist):
            return render(request, "hyperkitty/errors/private.html", {
                            "mlist": mlist,
                          }, status=403)


    query = ''
    results = EmptySearchQuerySet()
    sqs = RelatedSearchQuerySet()

    # Remove private non-subscribed lists
    if mlist is not None:
        sqs = sqs.filter(mailinglist__exact=mlist.name)
    else:
        excluded_mlists = MailingList.objects.filter(
            archive_policy=ArchivePolicy.private.value)
        if request.user.is_authenticated():
            subscriptions = request.user.hyperkitty_profile.get_subscriptions()
            excluded_mlists = excluded_mlists.exclude(
                name__in=subscriptions.keys())
        excluded_mlists = excluded_mlists.values_list("name", flat=True)
        sqs = sqs.exclude(mailinglist__in=excluded_mlists)

    # Sorting
    sort_mode = request.GET.get('sort')
    if sort_mode == "date-asc":
        sqs = sqs.order_by("date")
    elif sort_mode == "date-desc":
        sqs = sqs.order_by("-date")

    # Handle data
    if request.GET.get('q'):
        form = SearchForm(
            request.GET, searchqueryset=sqs, load_all=True)
        if form.is_valid():
            query = form.cleaned_data['q']
            results = form.search()
    else:
        form = SearchForm(searchqueryset=sqs, load_all=True)

    messages = paginate(results, page_num=request.GET.get('page'))
    for message in messages:
        if request.user.is_authenticated():
            message.object.myvote = message.object.votes.filter(user=request.user).first()
        else:
            message.object.myvote = None


    context = {
        'mlist' : mlist,
        'form': form,
        'messages': messages,
        'query': query,
        'sort_mode': sort_mode,
        'suggestion': None,
    }
    if results.query.backend.include_spelling:
        context['suggestion'] = form.get_suggestion()

    return render(request, "hyperkitty/search_results.html", context)