예제 #1
0
def show_talent_pool(request):
    categories = SkillCategory.objects.all()
    selected_skills = []
    people = TalentPeople.objects.all()
    
    template_name = "talentpool/main.html"
    if request.is_ajax():
        template_name = "talentpool/talent-main-mosaic.html"
    
    if request.method == "POST" and request.POST.getlist("skills"):
        selected_skills = [int(x) for x in request.POST.getlist("skills")]
        people = people.filter(skills__in=selected_skills)
        
    elif request.GET.get('q'):
        form = ModelSearchForm(request.GET, searchqueryset=None, load_all=True)
        searchqueryset = form.search()
        results = [ r.object.id for r in searchqueryset if issubclass(type(r.object), TalentPeople)]
        people = TalentPeople.objects.filter(id__in=results)
        selected_skills = []
    
    return render_to_response(template_name,
                              {'people' : people.distinct(),
                               'categories' : categories,
                               'selected_skills' : selected_skills},
                              context_instance=RequestContext(request))
예제 #2
0
def search(request,
           template='search/search.html',
           load_all=True,
           form_class=ModelSearchForm,
           searchqueryset=None,
           context_class=RequestContext,
           extra_context=None,
           results_per_page=None):

    query = ''
    results = EmptySearchQuerySet()

    # We have a query.
    if request.GET.get('q'):

        if request.user.is_authenticated() and '--mine' in request.GET.get(
                'q'):
            searchqueryset = SearchQuerySet().filter(
                author=request.user).order_by('-pub_date')
        else:
            searchqueryset = SearchQuerySet().filter(
                Q(public=True) | Q(author=request.user)).order_by('-pub_date')

        form = ModelSearchForm(request.GET,
                               searchqueryset=searchqueryset,
                               load_all=load_all)

        if form.is_valid():
            query = form.cleaned_data['q']
            results = form.search()
    else:
        form = form_class(searchqueryset=searchqueryset, load_all=load_all)

    paginator = Paginator(results, results_per_page or RESULTS_PER_PAGE)

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

    context = {
        'form': form,
        'has_snipts': True,
        'page': page,
        'paginator': paginator,
        'query': query,
        'suggestion': None,
    }

    if results.query.backend.include_spelling:
        context['suggestion'] = form.get_suggestion()

    if extra_context:
        context.update(extra_context)

    return render_to_response(template,
                              context,
                              context_instance=context_class(request))
예제 #3
0
def search(request):
    if (request.method == 'GET') | (request.method == 'POST'):
        page = request.GET.get('page')
        query = request.GET.get('q')
        _type = request.GET.get('t')

        results = SearchQuerySet().models(Asset)
        if _type == 'people':
            results = SearchQuerySet().models(User)
            for i in results:
                i.num_out = len(AssetCheckout.objects.filter(user=i.object.id).filter(in_date=None))
        else:
            _type = 'asset'
            for result in results:
                result.checkout_info = checkout_info(result)

        for x in request.GET.getlist('|'):
            results = results.filter(content=x)

        for x in request.GET.getlist('!'):
            results = results.exclude(content=x)

        if query:
            form = ModelSearchForm(
                    request.GET,
                    searchqueryset=results,
                    load_all=True
                    )
            if form.is_valid():
                query = form.cleaned_data['q']
                results = form.search()


        paginator = Paginator(results, SEARCH_RESULTS_PER_PAGE)

        try:
            page = paginator.page(page)
        except PageNotAnInteger:
            page = paginator.page(1)
        except EmptyPage:
            page = paginator.page(paginator.num_pages)

        x = (SEARCH_RESULTS_PER_PAGE * page.number)
        page.first = (SEARCH_RESULTS_PER_PAGE * (page.number - 1)) + 1
        page.last = x
        page.total = len(results)

        return render_to_response('Assets/search/%s_results.html' % _type, {'page': page},
                context_instance=RequestContext(request))
    else:
        return render_to_response('Assets/search/index.html',
                context_instance=RequestContext(request))
예제 #4
0
    def test_models_regression_1(self):
        # Regression for issue #1.
        msf = ModelSearchForm({
            'query': 'test',
            'models': ['core.mockmodel', 'core.anothermockmodel'],
        }, searchqueryset=self.sqs)

        self.assertEqual(msf.fields['models'].choices, [('core.anothermockmodel', u'Another mock models'), ('core.mockmodel', u'Mock models')])
        self.assertEqual(msf.errors, {})
        self.assertEqual(msf.is_valid(), True)

        sqs_with_models = msf.search()
        self.assertEqual(len(sqs_with_models.query.models), 2)
예제 #5
0
def search(request):
    query = request.GET.get("q", "")

    search_form = ModelSearchForm(request.GET, load_all=True)
    results = search_form.search()

    query_list = [x.object for x in results]
    players = [x for x in query_list if x.__class__ == Player]

    return render(request, "website/search.html", {
        "players": players,
        "search_query": query
    })
예제 #6
0
def search(request):
    query = request.GET.get('q', '')

    search_form = ModelSearchForm(request.GET, load_all=True)
    results = search_form.search()

    query_list = [x.object for x in results]
    players = [x for x in query_list if x.__class__ == Player]

    return render(request, 'website/search.html', {
        'players': players,
        'search_query': query
    })
예제 #7
0
 def test_models_regression_1(self):
     # Regression for issue #1.
     msf = ModelSearchForm({
         'query': 'test',
         'models': ['core.mockmodel', 'core.anothermockmodel'],
     }, searchqueryset=self.sqs)
     
     self.assertEqual(msf.fields['models'].choices, [('core.anothermockmodel', u'Another mock models'), ('core.mockmodel', u'Mock models')])
     self.assertEqual(msf.errors, {})
     self.assertEqual(msf.is_valid(), True)
     
     sqs_with_models = msf.search()
     self.assertEqual(len(sqs_with_models.query.models), 2)
예제 #8
0
def MySearchView(request):
    modelList = []
    if request.method == 'GET': # If the form has been submitted...
        form = ModelSearchForm(request.GET) # A form bound to the GET data
        if form.is_valid(): # All validation rules pass
            answer = form.cleaned_data['models']
            if answer == []:
                sqs = SearchQuerySet().models(Post, Comment)
            else:
                for model_name in answer:
                    # Turen a string into a class and create a list of model classes for sqs
                    ct = ContentType.objects.get(model=model_name.split(".")[1])
                    modelList.append(ct.model_class())
                sqs = SearchQuerySet().models(*modelList)
            search_view = MyHaystackSearchView(template = "blog/blog_search.html", searchqueryset=sqs)
            return search_view(request, "hello")
예제 #9
0
파일: views.py 프로젝트: bopopescu/bw
def homepage(request):
    #index 1
    recent_articles = Articles.objects.raw(
        "SELECT A.article_id,A.article_title, A.article_description,A.article_summary,C.category_id, C.category_name, AI.image_url, AI.photopath FROM articles A  LEFT JOIN article_category AC ON A.article_id = AC.article_id  LEFT JOIN channel_category C ON C.category_id = AC.category_id  JOIN article_images AI ON AI.article_id = A.article_id  WHERE A.display_to_homepage = '1' AND AI.photopath !='' GROUP BY A.article_id ORDER BY A.article_published_date DESC LIMIT 21"
    )
    recent_articles_rightsidebar = Articles.objects.raw(
        "SELECT A.*, AU.*, AI.image_url, AI.photopath, AV.video_embed_code FROM articles A LEFT JOIN article_author A_A ON A.article_id = A_A.article_id LEFT JOIN author AU ON A_A.author_id = AU.author_id JOIN article_images AI ON AI.article_id = A.article_id LEFT JOIN article_video AV ON A.article_id = AV.article_id WHERE A.display_to_homepage = '1' AND AI.photopath !='' GROUP BY A.article_id ORDER BY A.article_published_date DESC LIMIT 8"
    )
    recent_important_article = Articles.objects.raw(
        "SELECT A.article_id,A.article_title, A.article_description,A.article_summary, AU.*, AI.image_url, AI.photopath FROM articles A LEFT JOIN article_author A_A ON A.article_id = A_A.article_id LEFT JOIN author AU ON A_A.author_id = AU.author_id LEFT JOIN article_images AI ON A.article_id = AI.article_id WHERE A.display_to_homepage = '1'  AND A.important_article = 1 AND AI.photopath !='' GROUP BY A.article_id ORDER BY A.article_published_date DESC LIMIT 1"
    )

    bwtv_articles = VideoMaster.objects.raw(
        "SELECT * FROM video_master ORDER BY video_id DESC LIMIT 7")
    form = ModelSearchForm(searchqueryset=None, load_all=True)

    from django.db import connection

    connection.close()

    return render(
        request, 'homepage/onepage_index.html', {
            'recent_articles': recent_articles,
            'current_date_n_time': datetime.datetime.now(),
            'bwtv_articles': bwtv_articles,
            'recent_important_article': recent_important_article,
            'form': form,
        })
예제 #10
0
def search(request, template='search/search.html', load_all=True,
           form_class=ModelSearchForm, searchqueryset=None,
           context_class=RequestContext, extra_context=None,
           results_per_page=None):

    query = ''
    results = EmptySearchQuerySet()

    # We have a query.
    if request.GET.get('q'):

        if request.user.is_authenticated() and '--mine' in request.GET.get('q'):
            searchqueryset = SearchQuerySet().filter(author=request.user).order_by('-pub_date')
        else:
            searchqueryset = SearchQuerySet().filter(Q(public=True) | Q(author=request.user)).order_by('-pub_date')

        form = ModelSearchForm(request.GET, searchqueryset=searchqueryset, load_all=load_all)

        if form.is_valid():
            query = form.cleaned_data['q']
            results = form.search()
    else:
        form = form_class(searchqueryset=searchqueryset, load_all=load_all)

    paginator = Paginator(results, results_per_page or RESULTS_PER_PAGE)

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

    context = {
        'form': form,
        'has_snipts': True,
        'page': page,
        'paginator': paginator,
        'query': query,
        'suggestion': None,
    }

    if results.query.backend.include_spelling:
        context['suggestion'] = form.get_suggestion()

    if extra_context:
        context.update(extra_context)

    return render_to_response(template, context, context_instance=context_class(request))
예제 #11
0
def search(request):
    query = ''
    results = EmptySearchQuerySet()

    if request.GET.get('q'):
        form = ModelSearchForm(request.GET)

        if form.is_valid():
            query = form.cleaned_data['q']
            results = form.search().filter(network=request.network.parent)
    else:
        form = ModelSearchForm()

    paginator = Paginator(results, RESULTS_PER_PAGE)

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

    context = {
        'form': form,
        'page': page,
        'paginator': paginator,
        'query': query,
        'suggestion': None,
    }

    if getattr(settings, 'HAYSTACK_INCLUDE_SPELLING', False):
        context['suggestion'] = form.get_suggestion()

    return TemplateResponse(request, 'core/search.html', context)
예제 #12
0
def MySearchView(request):
    modelList = []
    if request.method == 'GET':  # If the form has been submitted...
        form = ModelSearchForm(request.GET)  # A form bound to the GET data
        if form.is_valid():  # All validation rules pass
            answer = form.cleaned_data['models']
            if answer == []:
                sqs = SearchQuerySet().models(Post, Comment)
            else:
                for model_name in answer:
                    # Turen a string into a class and create a list of model classes for sqs
                    ct = ContentType.objects.get(
                        model=model_name.split(".")[1])
                    modelList.append(ct.model_class())
                sqs = SearchQuerySet().models(*modelList)
            search_view = MyHaystackSearchView(
                template="blog/blog_search.html", searchqueryset=sqs)
            return search_view(request, "hello")
예제 #13
0
    def test_models_regression_1(self):
        # Regression for issue #1.
        msf = ModelSearchForm(
            {"query": "test", "models": ["core.mockmodel", "core.anothermockmodel"]},
            searchqueryset=self.sqs,
        )

        self.assertEqual(
            msf.fields["models"].choices,
            [
                ("core.anothermockmodel", "Another mock models"),
                ("core.mockmodel", "Mock models"),
            ],
        )
        self.assertEqual(msf.errors, {})
        self.assertEqual(msf.is_valid(), True)

        sqs_with_models = msf.search()
        self.assertEqual(len(sqs_with_models.query.models), 2)
예제 #14
0
    def test_models_regression_1(self):
        # Regression for issue #1.
        msf = ModelSearchForm(
            {"query": "test", "models": ["core.mockmodel", "core.anothermockmodel"]},
            searchqueryset=self.sqs,
        )

        self.assertEqual(
            msf.fields["models"].choices,
            [
                ("core.anothermockmodel", "Another mock models"),
                ("core.mockmodel", "Mock models"),
            ],
        )
        self.assertEqual(msf.errors, {})
        self.assertEqual(msf.is_valid(), True)

        sqs_with_models = msf.search()
        self.assertEqual(len(sqs_with_models.query.models), 2)
예제 #15
0
파일: views_search.py 프로젝트: erijpc/cmj
    def get_models(self):
        """Return a list of the selected models."""
        search_models = []

        if self.is_valid():
            for model in self.cleaned_data['models']:
                search_models.append(haystack_get_model(*model.split('.')))

        return search_models

        return ModelSearchForm.get_models(self)
예제 #16
0
class JsonSearchView(View):
    http_method_names = ['get']
    form = None
    queryset = []

    def dispatch(self, request, *args, **kwargs):
        self.form = ModelSearchForm(request.GET)
        return super(JsonSearchView, self).dispatch(request, *args, **kwargs)

    def get(self, *args, **kwargs):
        if self.form.is_valid():
            self.queryset = self.form.search()

        response = {}
        for result in self.queryset:
            if result.model_name in response:
                response[result.model_name].append(result.object.id)
            else:
                response[result.model_name] = [result.object.id]
        return JsonResponse(response)
예제 #17
0
    def post(self, request, load_all=True, searchqueryset=None):
        """
        首页查询功能
        :param request:
        :return:
        """
        # 127.0.0.1:8000/v1/goods/search/
        from dadashop.settings import HAYSTACK_SEARCH_RESULTS_PER_PAGE
        query = ''
        page_size = HAYSTACK_SEARCH_RESULTS_PER_PAGE
        results = EmptySearchQuerySet()
        if request.POST.get('q'):
            form = ModelSearchForm(request.POST,
                                   searchqueryset=searchqueryset,
                                   load_all=load_all)
            if form.is_valid():
                query = form.cleaned_data['q']
                results = form.search()
        else:
            form = ModelSearchForm(searchqueryset=searchqueryset,
                                   load_all=load_all)

        paginator = Paginator(results, page_size)
        try:
            page = paginator.page(int(request.POST.get('page', 1)))
        except:
            result = {'code': 40200, 'error': '页数有误,小于0或者大于总页数'}
            return JsonResponse(result)

        # 记录查询信息
        context = {
            'form': form,
            'page': page,
            'paginator': paginator,
            'query': query,
        }

        sku_list = []
        # print(len(page.object_list))
        for result in page.object_list:
            sku = {
                'skuid': result.object.id,
                'name': result.object.name,
                'price': result.object.price,
            }
            # 获取图片
            sku_image = str(result.object.default_image_url)
            sku['image'] = sku_image
            sku_list.append(sku)
        result = {
            "code": 200,
            "data": sku_list,
            'paginator': {
                'pagesize': page_size,
                'total': len(results)
            },
            'base_url': PIC_URL
        }
        return JsonResponse(result)
예제 #18
0
def post(request, ptype, pk):
    """Display a post form."""
    action = reverse("%s" % ptype, args=[pk])
    if ptype == "new_thread":
        title = "Start New Topic"
        subject = ''
        form = ThreadForm()
    elif ptype == "reply":
        title = "Reply to " + "\""+ Thread.objects.get(pk=pk).title + "\""
        subject = "Re: " + Thread.objects.get(pk=pk).title
        form = PostForm(initial={'title': subject})
    return render_to_response("forum/post.html", add_csrf(request, subject=subject,
        action=action, title=title, form=form, searchForm= ModelSearchForm()))
예제 #19
0
def search(request):
	query = ''
	results = EmptySearchQuerySet()
	
	if request.GET.get('q'):
		form = ModelSearchForm(request.GET)
		
		if form.is_valid():
			query = form.cleaned_data['q']
			results = form.search().filter(network = request.network.parent)
	else:
		form = ModelSearchForm()
	
	paginator = Paginator(results, RESULTS_PER_PAGE)
	
	try:
		page = paginator.page(
			int(request.GET.get('page', 1))
		)
	except InvalidPage:
		raise Http404('No such page')
	
	context = {
		'form': form,
		'page': page,
		'paginator': paginator,
		'query': query,
		'suggestion': None,
	}
	
	if getattr(settings, 'HAYSTACK_INCLUDE_SPELLING', False):
		context['suggestion'] = form.get_suggestion()
	
	return TemplateResponse(
		request,
		'core/search.html',
		context
	)
예제 #20
0
def post(request, pk):
    """Single post with comments and a comment form."""
    """post below gets the title of the post. note: Post.objects.get()"""
    post = Post.objects.get(pk=int(pk))
    comments = Comment.objects.filter(title=post)
    d = {
        "post": post,
        "user": request.user,
        "months": mkmonth_lst(),
        "comments": comments,
        "form": CommentForm(),
        "searchForm": ModelSearchForm()
    }
    d.update(csrf(request))
    return render_to_response("blog/post.html", d)
예제 #21
0
def thread(request, pk):
    """Listing of posts in a thread. The first post is always the thread post."""
    thread = Post.objects.filter(thread=pk).order_by("created")[0]
    posts = Post.objects.filter(thread=pk).order_by("created")[1:]
    posts = mk_paginator(request, posts, 15)
    title = Thread.objects.get(pk=pk).title
    
    """creates the paginator with 2 items per page."""
    #paginator = Paginator(posts, 3)
    #
    #try: page = int(request.GET.get("page", '1'))
    #except ValueError: page = 1
    #
    #try:
    #    posts = paginator.page(page)
    #except (InvalidPage, EmptyPage):
    #    posts = paginator.page(paginator.num_pages)
        
    return render_to_response("forum/thread.html", add_csrf(request, thread=thread, posts=posts, pk=pk,
        title=title, searchForm= ModelSearchForm()))
예제 #22
0
def main(request):
    """Main listing."""
    """The list of posts is ordered by created time in reverse order."""
    posts = Post.objects.all().order_by("-created")
    """creates the paginator with 2 items per page."""
    paginator = Paginator(posts, 3)

    try:
        page = int(request.GET.get("page", '1'))
    except ValueError:
        page = 1

    try:
        posts = paginator.page(page)
    except (InvalidPage, EmptyPage):
        posts = paginator.page(paginator.num_pages)

    d = {
        "posts": posts,
        "user": request.user,
        "months": mkmonth_lst(),
        "searchForm": ModelSearchForm()
    }
    return render_to_response("blog/list.html", d)
예제 #23
0
 def dispatch(self, request, *args, **kwargs):
     self.form = ModelSearchForm(request.GET)
     return super(JsonSearchView, self).dispatch(request, *args, **kwargs)
예제 #24
0
파일: views.py 프로젝트: nicksergeant/snipt
def search(
    request,
    template="search/search.html",
    load_all=True,
    form_class=ModelSearchForm,
    searchqueryset=None,
    context_class=RequestContext,
    extra_context=None,
    results_per_page=None,
):

    query = ""
    results = EmptySearchQuerySet()

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

        searchqueryset = SearchQuerySet().filter(Q(public=True) | Q(author=request.user)).order_by("-pub_date")

        if request.user.is_authenticated() and "mine-only" in request.GET:
            searchqueryset = SearchQuerySet().filter(author=request.user).order_by("-pub_date")

        elif request.user.is_authenticated() and ("author" in request.GET and request.GET.get("author")):

            author = request.GET.get("author")

            if author == request.user.username:
                searchqueryset = SearchQuerySet().filter(author=request.user).order_by("-pub_date")

            else:
                team = get_object_or_None(Team, slug=author)

                if team and team.user_is_member(request.user):
                    searchqueryset = SearchQuerySet().filter(author=team).order_by("-pub_date")

        form = ModelSearchForm(request.GET, searchqueryset=searchqueryset, load_all=load_all)

        if form.is_valid():
            query = form.cleaned_data["q"]
            results = form.search()
    else:
        form = form_class(searchqueryset=searchqueryset, load_all=load_all)

    paginator = Paginator(results, results_per_page or RESULTS_PER_PAGE)

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

    context = {
        "form": form,
        "has_snipts": True,
        "page": page,
        "paginator": paginator,
        "query": query,
        "suggestion": None,
    }

    if results.query.backend.include_spelling:
        context["suggestion"] = form.get_suggestion()

    if extra_context:
        context.update(extra_context)

    return render(request, template, context)
예제 #25
0
def forum(request, pk):
    """Listing of threads in a forum."""
    threads = Thread.objects.filter(forum=pk).order_by("-created")
    threads = mk_paginator(request, threads, 20)
    return render_to_response("forum/forum.html", add_csrf(request, threads=threads, pk=pk, searchForm= ModelSearchForm()))
예제 #26
0
 def extra_context(self):
     return {"months": mkmonth_lst(), "searchForm": ModelSearchForm()}
예제 #27
0
def main(request):
    """Main listing."""
    forums = Forum.objects.all()
    d = {"forums": forums, "user": request.user, "searchForm": ModelSearchForm()}
    return render_to_response("forum/list.html", d)
예제 #28
0
def MyForumSearchView(request):
    form = ModelSearchForm(request.GET) # A form bound to the GET data
    if form.is_valid(): # All validation rules pass
        sqs = SearchQuerySet().models(Post)
        search_view = SearchView(template = "forum/forum_search.html", searchqueryset=sqs)
        return search_view(request)
예제 #29
0
def keywordResult(request):
    modelList = []
    answer = []
    keywords_dictionary = {}
    keywords_origList = []
    keywordsList = []
    keywords = ""

    try:
        request.session['selectedRoutines']
        request.session['scriptOutput']
        request.session['userScript']
    except (NameError, KeyError):
        request.session['selectedRoutines'] = []
        request.session['scriptOutput'] = ""
        request.session['userScript'] = ""

    if request.method == 'POST':
        form = ModelSearchForm(request.POST)
        #print form

        if form.is_valid():
            ## if driver/computational boxes are checked
            #answer_class = form.cleaned_data['models']

            ## get the keyword
            keywords_orig = request.POST['q']

            ## Don't split double-quoted words ##
            keywords_origList = shlex.split(keywords_orig)

            ## split all words ##
            keywords_singleList = keywords_orig.split()

            ## spell check ##
            for i, item in enumerate(keywords_singleList):
                keywords_singleList[i] = spell_check(item)

            ## make a string out of keywordsList ##
            keywords = " ".join(keywords_singleList)

            ## keywords goes through keyword_handler ##
            keywords = keyword_handler(keywords)
            #print keywords

            ## final keywordsList, Don't split double-quoted words
            keywordsList = shlex.split(keywords)

            ## find the words that are not corrected ##
            common = list(set(keywords_origList) & set(keywordsList))
            #print common

            ###***** make a dictionary for the keywords for django query *****###
            sumList = []
            for key in special_words:
                keywords_dictionary[key] = list(
                    set(keywordsList) & set(special_words[key]))
                sumList += keywords_dictionary[key]
            keywords_dictionary['other'] = list(
                set(keywordsList) - set(sumList))

            ## keep 'transpose' and 'conjugate transpose' only
            keywords_dictionary['other'] = list(
                set(['transpose', 'conjugate transpose'])
                & set(keywords_dictionary['other']))
            print keywords_dictionary

            if not any([
                    keywords_dictionary[i] == []
                    for i in ['table', 'matrixType']
            ]):
                print 'use django'
                keywords_dictionary = keyword_handler2(keywords_dictionary)
                keywords_dictionary = kwDictionary_set(keywords_dictionary)
                #print keywords_dictionary
                results = query_django(keywords_dictionary)
            else:
                print 'use haystack'
                results = SearchQuerySet().models(least).filter(
                    content=AutoQuery(keywords)).order_by('id')

            context = {
                'results': results,
                'keywordsList': keywordsList,
                'common': common,
                'selectedRoutines': request.session['selectedRoutines'],
                #'notSelectedRoutines': request.session['notSelectedRoutines'],
            }

            return render_to_response('orthg/keywordResult.html',
                                      {'KeywordTab': True},
                                      context_instance=RequestContext(
                                          request, context))
        else:
            HttpResponse("Error!")
예제 #30
0
def keywordResult(request):
	modelList = []
	answer = []
	keywords_dictionary = {}
	keywords_origList = []
	keywordsList = []
	keywords = ""

	try:
		request.session['selectedRoutines']
		request.session['scriptOutput']
		request.session['userScript']	
	except (NameError,KeyError):
		request.session['selectedRoutines'] = []
		request.session['scriptOutput'] = ""
		request.session['userScript'] = ""
	
	if request.method == 'POST':		
		form = ModelSearchForm(request.POST)
		#print form
		
		if form.is_valid():
			## if driver/computational boxes are checked
			#answer_class = form.cleaned_data['models']
				
			## get the keyword
			keywords_orig = request.POST['q']
			
			## Don't split double-quoted words ##
			keywords_origList = shlex.split(keywords_orig)
			
			## split all words ##
			keywords_singleList = keywords_orig.split()
			
			## spell check ##
			for i, item in enumerate(keywords_singleList):
				keywords_singleList[i] = spell_check(item)	
				
			## make a string out of keywordsList ##
			keywords = " ".join(keywords_singleList)
			
			## keywords goes through keyword_handler ##
			keywords = keyword_handler(keywords)
			#print keywords
			
			## final keywordsList, Don't split double-quoted words
			keywordsList = shlex.split(keywords)
			
			## find the words that are not corrected ##
			common = list(set(keywords_origList) & set(keywordsList))
			#print common
			
			
			###***** make a dictionary for the keywords for django query *****###
			sumList = []
			for key in special_words:
				keywords_dictionary[key] = list(set(keywordsList) & set(special_words[key]))
				sumList += keywords_dictionary[key]
			keywords_dictionary['other'] = list(set(keywordsList) - set(sumList))
			
			## keep 'transpose' and 'conjugate transpose' only
			keywords_dictionary['other'] = list(set(['transpose', 'conjugate transpose']) & set(keywords_dictionary['other']))
			print keywords_dictionary
			
			if not any([keywords_dictionary[i] == [] for i in ['table', 'matrixType']]):
				print 'use django'
				keywords_dictionary = keyword_handler2(keywords_dictionary)
				keywords_dictionary = kwDictionary_set(keywords_dictionary)
				#print keywords_dictionary
				results = query_django(keywords_dictionary)				
			else:
				print 'use haystack'
				results = SearchQuerySet().models(lapack_le_driver, lapack_le_computational).filter(content=AutoQuery(keywords)).order_by('id')
							
			
			context = {'results': results,
				   'keywordsList': keywordsList,
				   'common': common,
				   'selectedRoutines': request.session['selectedRoutines'],
				   #'notSelectedRoutines': request.session['notSelectedRoutines'],
				   }
			
			return render_to_response(
				'lighthouse/lapack_le/keywordResult.html', 
				{'KeywordTab': True}, 
				context_instance=RequestContext(request, context)
			)
		else:
			HttpResponse("Error!")
예제 #31
0
def search(request,
           template='search/search.html',
           load_all=True,
           form_class=ModelSearchForm,
           searchqueryset=None,
           context_class=RequestContext,
           extra_context=None,
           results_per_page=None):

    query = ''
    results = EmptySearchQuerySet()

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

        searchqueryset = SearchQuerySet() \
            .filter(Q(public=True) | Q(author=request.user)) \
            .order_by('-pub_date')

        if request.user.is_authenticated() and \
                'mine-only' in request.GET:
            searchqueryset = SearchQuerySet().filter(author=request.user) \
                .order_by('-pub_date')

        elif request.user.is_authenticated() and \
                ('author' in request.GET and
                    request.GET.get('author')):

            author = request.GET.get('author')

            if author == request.user.username:
                searchqueryset = SearchQuerySet().filter(author=request.user) \
                    .order_by('-pub_date')

            else:
                team = get_object_or_None(Team, slug=author)

                if team and team.user_is_member(request.user):
                    searchqueryset = SearchQuerySet().filter(author=team) \
                        .order_by('-pub_date')

        form = ModelSearchForm(request.GET,
                               searchqueryset=searchqueryset,
                               load_all=load_all)

        if form.is_valid():
            query = form.cleaned_data['q']
            results = form.search()
    else:
        form = form_class(searchqueryset=searchqueryset, load_all=load_all)

    paginator = Paginator(results, results_per_page or RESULTS_PER_PAGE)

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

    context = {
        'form': form,
        'has_snipts': True,
        'page': page,
        'paginator': paginator,
        'query': query,
        'suggestion': None,
    }

    if results.query.backend.include_spelling:
        context['suggestion'] = form.get_suggestion()

    if extra_context:
        context.update(extra_context)

    return render(request, template, context)