1 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
4 from django.conf import settings
5 from django.shortcuts import render
6 from django.views.decorators import cache
7 from django.http import HttpResponse, JsonResponse
9 from catalogue.models import Book, Tag
10 from .forms import SearchFilters
14 from wolnelektury.utils import re_escape
17 query_syntax_chars = re.compile(r"[\\/*:(){}?.[\]+]")
20 def remove_query_syntax_chars(query, replace=' '):
21 return query_syntax_chars.sub(replace, query)
25 def hint(request, mozhint=False, param='term'):
26 prefix = request.GET.get(param, '')
28 return JsonResponse([], safe=False)
30 prefix = re_escape(' '.join(remove_query_syntax_chars(prefix).split()))
33 limit = int(request.GET.get('max', ''))
40 authors = Tag.objects.filter(
41 category='author', name_pl__iregex='\m' + prefix).only('name', 'id', 'slug', 'category')
46 'url': author.get_absolute_url(),
48 for author in authors[:limit]
51 for b in Book.objects.filter(findable=True, title__iregex='\m' + prefix)[:limit-len(data)]:
52 author_str = b.author_unicode()
53 translator = b.translator()
55 author_str += ' (tłum. ' + translator + ')'
61 'url': b.get_absolute_url()
74 callback = request.GET.get('callback', None)
76 return HttpResponse("%s(%s);" % (callback, json.dumps(data)),
77 content_type="application/json; charset=utf-8")
79 return JsonResponse(data, safe=False)
85 filters = SearchFilters(request.GET)
87 'title': 'Wynik wyszukiwania',
88 'query': request.GET.get('q', ''),
91 if filters.is_valid():
92 ctx['results'] = filters.results()
93 for k, v in ctx['results'].items():
95 ctx['hasresults'] = True
97 return render(request, 'search/results.html', ctx)