bgneal@763
|
1 """Custom views for searching."""
|
bgneal@961
|
2 import logging
|
bgneal@763
|
3
|
bgneal@961
|
4 from django.shortcuts import render_to_response
|
bgneal@763
|
5 from haystack.views import SearchView
|
bgneal@961
|
6 from xapian import QueryParserError
|
bgneal@763
|
7
|
bgneal@961
|
8 logger = logging.getLogger(__name__)
|
bgneal@763
|
9
|
bgneal@763
|
10 class UserSearchView(SearchView):
|
bgneal@763
|
11 """This class passes the user making the search as an __init__ argument to
|
bgneal@763
|
12 the search form as the keyword argument 'user'.
|
bgneal@763
|
13
|
bgneal@763
|
14 """
|
bgneal@961
|
15 query_parser_error = False
|
bgneal@961
|
16
|
bgneal@763
|
17 def build_form(self, form_kwargs=None):
|
bgneal@763
|
18 """Pass the request.user object to the form's constructor."""
|
bgneal@763
|
19 if not form_kwargs:
|
bgneal@763
|
20 form_kwargs = {}
|
bgneal@763
|
21 if 'user' not in form_kwargs:
|
bgneal@763
|
22 form_kwargs['user'] = self.request.user
|
bgneal@763
|
23 return super(UserSearchView, self).build_form(form_kwargs)
|
bgneal@961
|
24
|
bgneal@961
|
25 # This nonsense is because Xapian can raise QueryParserError when evaluating
|
bgneal@961
|
26 # the query. This was triggered by some sh*t-bag looking for SQL injection
|
bgneal@961
|
27 # vulnerabilities.
|
bgneal@961
|
28 # If QueryParserError is raised, just drive on and set a flag in the context
|
bgneal@961
|
29 # (via extra_context()) so that an error is rendered on the template instead
|
bgneal@961
|
30 # of a 500 error.
|
bgneal@961
|
31
|
bgneal@961
|
32 def create_response(self):
|
bgneal@961
|
33 try:
|
bgneal@961
|
34 return super(UserSearchView, self).create_response()
|
bgneal@961
|
35 except QueryParserError:
|
bgneal@961
|
36 self.query_parser_error = True
|
bgneal@961
|
37
|
bgneal@961
|
38 logger.warning("QueryParserError triggered from user search input")
|
bgneal@961
|
39
|
bgneal@961
|
40 context = {
|
bgneal@961
|
41 'query': self.query,
|
bgneal@961
|
42 'form': self.form,
|
bgneal@961
|
43 'page': None,
|
bgneal@961
|
44 'paginator': None,
|
bgneal@961
|
45 'suggestion': None,
|
bgneal@961
|
46 }
|
bgneal@961
|
47
|
bgneal@961
|
48 context.update(self.extra_context())
|
bgneal@961
|
49 return render_to_response(self.template, context,
|
bgneal@961
|
50 context_instance=self.context_class(self.request))
|
bgneal@961
|
51
|
bgneal@961
|
52 def extra_context(self):
|
bgneal@961
|
53 return {
|
bgneal@961
|
54 'query_parser_error': self.query_parser_error,
|
bgneal@961
|
55 }
|