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

    if request.POST:
        form = SearchForm(request.POST)
        if form.is_valid():
            #Based on http://stackoverflow.com/questions/1957240/filter-using-q-object-with-dynamic-from-user/1957263#1957263
            queryset = form.cleaned_data['search_field'].split()
            query = reduce(operator.or_, ((Q(title__icontains = x) | Q(description__icontains = x)) for x in queryset))
            #results = Image.objects.filter(Q(title__iexact = query) | Q(description__icontains = query))
            results = Image.objects.filter(query)
        else:
            results = []
    else:
        form = SearchForm()
        results = []
    
    #results = Image.objects.all()


    return render_to_response(
        'search.html',
        RequestContext(request, {
            'form': form,
            'search_results': results,
        })
    )
Ejemplo n.º 2
0
def result(username, query):
    per_page = app.config['POSTS_PER_PAGE']

    form = SearchForm()
    user = User.query.filter_by(username=username).first()
    query__ = query

    if form.validate_on_submit():
        new_query = form.query.data
        return redirect(url_for('result', username=username, query=new_query))

    cur_page = request.args.get('page', 1, type=int)
    #problems_, total = Problem.search(query__, 1, len(Problem.query.all()))
    problems_, total = Problem.search(query__, cur_page, per_page)
    problems = problems_.all()
    #problems = paginate(pp, cur_page, per_page)
    last_page = math.ceil(len(problems) / per_page)

    next_url = url_for('result', username=user.username, page=cur_page+1, query=query__) \
        if total > cur_page*per_page else None

    prev_url = url_for('result', username=user.username, page=cur_page-1, query=query__) \
        if cur_page > 1 else None
    return render_template('user_result.html',
                           user=user,
                           form=form,
                           problems=problems,
                           next_url=next_url,
                           prev_url=prev_url)
Ejemplo n.º 3
0
def search(request):

    if request.POST:
        form = SearchForm(request.POST)
        if form.is_valid():
            #Based on http://stackoverflow.com/questions/1957240/filter-using-q-object-with-dynamic-from-user/1957263#1957263
            queryset = form.cleaned_data['search_field'].split()
            query = reduce(
                operator.or_,
                ((Q(title__icontains=x) | Q(description__icontains=x))
                 for x in queryset))
            #results = Image.objects.filter(Q(title__iexact = query) | Q(description__icontains = query))
            results = Image.objects.filter(query)
        else:
            results = []
    else:
        form = SearchForm()
        results = []

    #results = Image.objects.all()

    return render_to_response(
        'search.html',
        RequestContext(request, {
            'form': form,
            'search_results': results,
        }))
Ejemplo n.º 4
0
def home():
    if current_user.is_authenticated:
        return redirect(url_for('user',username=current_user.username))
    form = SearchForm()
    if form.validate_on_submit():
        return redirect(url_for('about'))

    return render_template('home.html', form=form)
Ejemplo n.º 5
0
def user(username):
    user = User.query.filter_by(username=username).first()
    form = SearchForm()
    if form.validate_on_submit():
        query = form.query.data
        return redirect(url_for('result', username=username, query=query))

    return render_template('user.html', user=user, form=form)
Ejemplo n.º 6
0
def search(request):
    """Renders page with search results"""
    if not request.method == 'GET':
        return HttpResponseNotAllowed(['GET'])

    params = request.GET
    flights = Flight.objects.all()

    if params.get('day_from', '') == '' and params.get('day_to', '') == '':
        flights = flights.filter(day_from=datetime.now().date(), day_to=datetime.now().date())

    if params.get('airport_from', '') != '':
        flights = flights.filter(airport_from=params['airport_from'])
    if params.get('airport_to', '') != '':
        flights = flights.filter(airport_to=params['airport_to'])
    if params.get('day_from', '') != '':
        flights = flights.filter(day_from__gte=datetime.strptime(params['day_from'], '%Y-%m-%d'))
    if params.get('day_to', '') != '':
        flights = flights.filter(day_to__lte=datetime.strptime(params['day_to'], '%Y-%m-%d'))

    flights = flights.values()
    search_form = SearchForm(initial={
        'airport_from': params.get('airport_from', ''),
        'airport_to': params.get('airport_to', ''),
        'day_from': params.get('day_from', ''),
        'day_to': params.get('day_to', '')
    })

    return render(request, 'search.html',
                  {'request': request, 'flights': flights, 'search_form': search_form})
Ejemplo n.º 7
0
 def create_search_form(self,
                        search_by=0,
                        fbm=None,
                        fbm_filename=None,
                        fbm_uploader=None,
                        fbm_upload_date_start=None,
                        fbm_upload_date_end=None,
                        fbc=None,
                        fbc_council=None,
                        fbc_publish_date_start=None,
                        fbc_publish_date_end=None,
                        key_phrase1=None,
                        key_phrase_type1=None,
                        key_phrase_importance1=None):
     """ Creates a default search form with a set of default (valid) values. """
     return SearchForm({
         'search_by': search_by,
         'fbm': fbm,
         'fbm_filename': fbm_filename,
         'fbm_uploader': fbm_uploader,
         'fbm_upload_date_start': fbm_upload_date_start,
         'fbm_upload_date_end': fbm_upload_date_end,
         'fbc': fbc,
         'fbc_council': fbc_council,
         'fbc_publish_date_start': fbc_publish_date_start,
         'fbc_publish_date_end': fbc_publish_date_end,
         'key_phrase1': key_phrase1,
         'key_phrase_type1': key_phrase_type1,
         'key_phrase_importance1': key_phrase_importance1
     })
Ejemplo n.º 8
0
def index():
    form = SearchForm(request.args)
    query = form.data['q']
    table = None
    if query is not None:
        items = Card.query.filter(Card.name.like('%'+query+'%')).all()
        table = ItemTable(items)
    return render_template('index.html', form=form, query=query, table=table)
Ejemplo n.º 9
0
def search():
    form = SearchForm(request.args)
    select = form.select.data
    query = request.args.get('q', None)
    table = None
    if query is not None:
        if select == 'Heirloom':
            items = Card.query.filter(Card.name.like('%'+query+'%')).filter(Card.heirloom_legal == 1).all()
        else:
            items = Card.query.filter(Card.name.like('%'+query+'%')).all()
        table = ItemTable(items)
    return render_template('index.html', form=form, query=query, table=table)
Ejemplo n.º 10
0
def search(request):
    """A view that displays the product search."""
    if request.method == 'POST':
        form = SearchForm(request.POST)
        if form.is_valid():
            search_prod = form.cleaned_data['search']
            product = Product.objects.\
                filter(name__icontains=search_prod).first()
            if product is not None:
                subsitutes = Product.objects.filter(
                    Q(nutri_score__lte=product.nutri_score),
                    Q(category__in=product.category.all())).\
                    distinct('name', 'nutri_score').order_by('nutri_score')

                return render(request, 'search.html', {'search': search_prod,
                                                       'products': subsitutes,
                                                       'form': form})
            else:
                render(request, 'search.html', {'search': search_prod,
                                                'products': product,
                                                'form': form})
    else:
        form = SearchForm()
    return render(request, 'search.html', {'form': form})
Ejemplo n.º 11
0
def search(request):
    if request.method != "GET":
        return HttpResponse("request method needs to be GET")
    else:
        bound_search_form = SearchForm(request.GET)
        query = request.GET.get('query', False)
        subject = request.GET.get('subject')
        kwargs = {}
        args = []
        if query:
            query_word_list = query.split()
            args.append(reduce(operator.or_, ((
                Q(title__contains=x) | Q(content__contains=x)) for x in query_word_list)))

        if subject:
            kwargs['subject__name'] = subject

        summaries_list = Summary.objects.sortedByScore(*args, **kwargs)

        # get any current GET queries without the page modifier
        queries_without_page = request.GET.copy()
        if 'page' in queries_without_page.keys():
            del queries_without_page['page']

        length = len(summaries_list)

        # pagination
        paginator = Paginator(summaries_list, 10)

        # get page number from GET request
        page_num = request.GET.get('page', 1)

        # get summaries from paginator according to page number
        try:
            summaries = paginator.page(page_num)
        except(EmptyPage, InvalidPage):
            summaries = paginator.page(paginator.num_pages)

        context_dict = {
            'sumAmount': length,
            'summaries': summaries,
            'search_form': bound_search_form,
            'params': queries_without_page,
        }

        return render(request, 'search.html', context_dict)
Ejemplo n.º 12
0
def home():
    form = SearchForm()
    return render_template('home.html', form=form)
Ejemplo n.º 13
0
def subcategory(request,
                category_name_slug,
                subcategory_name_slug,
                template='website/subcategory.html',
                extra_context=None):
    context_dict = {}
    # set the initial using what was sent in the get request
    form = DateFilterForm(initial=request.GET)
    context_dict['form'] = form
    search_form = SearchForm(initial=request.GET)
    context_dict['search_form'] = search_form
    # get todays date for filtering recommendations by
    today = date.today()

    try:
        user = request.user
        category = Category.objects.get(slug=category_name_slug)
        context_dict['category'] = category
        subcategory = SubCategory.objects.get(slug=subcategory_name_slug,
                                              category=category)
        context_dict['subcategory_name'] = subcategory.name
        context_dict['subcategory'] = subcategory
        website_list = (WebsiteRecommendation.objects.filter(
            subcategory=subcategory).annotate(
                totalvotes=Count('upvote') -
                Count('downvote')).order_by('-totalvotes'))
        context_dict['websites'] = website_list
        book_list = (BookRecommendation.objects.filter(
            subcategory=subcategory).annotate(
                totalvotes=Count('upvote') -
                Count('downvote')).order_by('-totalvotes'))
        context_dict['books'] = book_list
        video_list = (VideoRecommendation.objects.filter(
            subcategory=subcategory).annotate(
                totalvotes=Count('upvote') -
                Count('downvote')).order_by('-totalvotes'))
        context_dict['videos'] = video_list

    except SubCategory.DoesNotExist:
        raise Http404

    except Category.DoesNotExist:
        raise Http404

    if request.method == 'GET':
        form = DateFilterForm(request.GET)

        if form.is_valid():
            filter_type = (form.cleaned_data['time_filter'])

            if filter_type == 'newest':
                website_list = (WebsiteRecommendation.objects.filter(
                    subcategory=subcategory).order_by('-created_date'))
                context_dict['websites'] = website_list
                book_list = (BookRecommendation.objects.filter(
                    subcategory=subcategory).order_by('-created_date'))
                context_dict['books'] = book_list
                video_list = (VideoRecommendation.objects.filter(
                    subcategory=subcategory).order_by('-created_date'))
                context_dict['videos'] = video_list
            elif filter_type == 'best-of-year':
                website_list = (WebsiteRecommendation.objects.filter(
                    subcategory=subcategory,
                    created_date__year=today.year).annotate(
                        totalvotes=Count('upvote') -
                        Count('downvote')).order_by('-totalvotes'))
                context_dict['websites'] = website_list
                book_list = (BookRecommendation.objects.filter(
                    subcategory=subcategory,
                    created_date__year=today.year).annotate(
                        totalvotes=Count('upvote') -
                        Count('downvote')).order_by('-totalvotes'))
                context_dict['books'] = book_list
                video_list = (VideoRecommendation.objects.filter(
                    subcategory=subcategory,
                    created_date__year=today.year).annotate(
                        totalvotes=Count('upvote') -
                        Count('downvote')).order_by('-totalvotes'))
                context_dict['videos'] = video_list
            elif filter_type == 'best-of-month':
                website_list = (WebsiteRecommendation.objects.filter(
                    subcategory=subcategory,
                    created_date__year=today.year,
                    created_date__month=today.month).annotate(
                        totalvotes=Count('upvote') -
                        Count('downvote')).order_by('-totalvotes'))
                context_dict['websites'] = website_list
                book_list = (BookRecommendation.objects.filter(
                    subcategory=subcategory,
                    created_date__year=today.year,
                    created_date__month=today.month).annotate(
                        totalvotes=Count('upvote') -
                        Count('downvote')).order_by('-totalvotes'))
                context_dict['books'] = book_list
                video_list = (VideoRecommendation.objects.filter(
                    subcategory=subcategory,
                    created_date__year=today.year,
                    created_date__month=today.month).annotate(
                        totalvotes=Count('upvote') -
                        Count('downvote')).order_by('-totalvotes'))
                context_dict['videos'] = video_list

        search_form = SearchForm(request.GET)
        if search_form.is_valid():
            search_keywords = (search_form.cleaned_data['search_box'])
            context_dict['search_keywords'] = search_keywords

            if search_keywords != '':
                # add weighting to gear more towards title?
                website_list = (WebsiteRecommendation.objects.annotate(
                    search=SearchVector('title', 'description'), ).filter(
                        subcategory=subcategory,
                        search=SearchQuery(search_keywords)))
                context_dict['websites'] = website_list
                book_list = (BookRecommendation.objects.annotate(
                    search=SearchVector('title', 'book_description'), ).filter(
                        subcategory=subcategory,
                        search=SearchQuery(search_keywords)))
                context_dict['books'] = book_list
                video_list = (VideoRecommendation.objects.annotate(
                    search=SearchVector(
                        'title', 'video_description'), ).filter(
                            subcategory=subcategory,
                            search=SearchQuery(search_keywords)))
                context_dict['videos'] = video_list

    if extra_context is not None:
        context_dict.update(extra_context)
    return render(request, template, context_dict)
Ejemplo n.º 14
0
def search(request, search_string=None, title='Search', words=None):
    
    r_server = _get_redis()
        
    # replace search string underscores with spaces
    if search_string:
        search_string = search_string.strip().replace('_', ' ')        
               

    # HANDLES EMPTY OR NULL SEARCH STRING
    if search_string == None and request.method != 'POST':
        form = SearchForm()
        return _render(request, 'website/search.html', locals())
          
          
    # CHECK IF IT'S A POST REQUEST OR URL SEARCH
    if search_string == None and request.method == 'POST':
        form = SearchForm(request.POST)
        if form.is_valid():
            search_string = form.cleaned_data['char']

        else:
            # POST AND NO SEARCH STRING - SHOW THEM THE PLAIN JANE SEARCH PAGE
            form = SearchForm()
            return _render(request, 'website/search.html', locals())


    # HANDLES AN AMBIGUOUS SEARCH
    if _is_ambiguous(search_string):
        message = messages.AMBIGUOUS_WORD
        return render(request, 'problem.html', locals())


    if r_server.exists((settings.PINYIN_WORD_KEY % _pinyin_to_ascii(search_string))):  
        return _pinyin_search(request, search_string)


    if _is_english(search_string):
        return _english_search(request, search_string)


    # IF THE SEARCH IS OVER 10 CHARACTERS, RETURN A TEXT
    #if len(search_string) > 12:
    #    from creader.views import text                
    #    return text(request, words=search_string)
    
    
    if not words:
        things = _split_unicode_chrs(search_string)        
        words = _group_words(things)   

        
    # IF THE USER WAS LOGGED IN, RECORD IT IN THEIR 'SAVED WORDS'
    if request.user.is_authenticated():
        for x in words:
            word_searched.send(
                sender=word_searched, 
                word=x.chars, 
                time=datetime.datetime.now(), 
                user_id=request.user.email
            )
    
    
    # if there's only 1 word, take us straight to the single word definition
    if len(words) == 1:
        word = words[0]
        url = reverse('single_word', args=[word])
        return HttpResponseRedirect(url)
    
    return _render(request, 'website/wordlist.html', locals())
Ejemplo n.º 15
0
 def test_search_form_search_field_label(self):
     form = SearchForm()
     self.assertTrue(form.fields['search'].label is None
                     or form.fields['search'].label == 'Produit recherché')
Ejemplo n.º 16
0
def home():
    form = SearchForm()
    if form.validate_on_submit():
        return redirect(url_for('about'))

    return render_template('home.html', form=form)
Ejemplo n.º 17
0
 def test_search_form_search_field_max_length(self):
     form = SearchForm()
     self.assertEqual(form.fields['search'].max_length, 100)