recherche: première ébauche
[auf_framonde.git] / project / aldryn_search / views.py
CommitLineData
5f23ec55
PH
1# -*- coding: utf-8 -*-
2import datetime
3
4from django.views.generic import ListView
5from django.views.generic.edit import FormMixin
6
7from django import forms
8
9from haystack.forms import SearchForm
10from haystack.query import SearchQuerySet
11
12
13from aldryn_common.paginator import DiggPaginator
14
15from .conf import settings
16
17
18class AldrynFacetedSearchForm(SearchForm):
19 selected_facets = forms.CharField(required=False, widget=forms.HiddenInput)
20 courant = forms.BooleanField(required=False, widget=forms.HiddenInput)
21 cloture = forms.BooleanField(required=False, widget=forms.HiddenInput)
22
23 def search(self):
24 sqs = SearchQuerySet()
25 sqs = sqs.facet('bureaux').facet(
26 'section').facet('annee').facet('partenaire')
27
28 if self.q:
29 sqs = sqs.filter(content=sqs.query.clean(self.q))
30
31 if self.courant:
32 sqs = sqs.filter(date_fin__gte=datetime.date.today())
33 if self.cloture:
34 sqs = sqs.filter(date_fin__lt=datetime.date.today())
35
36 self.selected_facets = list(
37 set(self.selected_facets.split('&') + self.selected_facets_get))
38
39 for facet in self.selected_facets:
40 if "__" not in facet:
41 continue
42
43 field, value = facet.split("__", 1)
44
45 if value:
46 sqs = sqs.narrow(u'%s:"%s"' % (field, sqs.query.clean(value)))
47
48 return sqs
49
50
51class AldrynSearchView(FormMixin, ListView):
52 form_class = AldrynFacetedSearchForm
53
54 paginate_by = settings.ALDRYN_SEARCH_PAGINATION
55 paginator_class = DiggPaginator
56
57 template_name = 'aldryn_search/search_results.html'
58
59 def get(self, request, *args, **kwargs):
60 self.form = AldrynFacetedSearchForm(self.request.GET)
61 self.form.q = self.request.GET.get('q', '')
62 self.form.courant = self.request.GET.get('courant', '')
63 self.form.cloture = self.request.GET.get('cloture', '')
64 self.form.selected_facets = self.request.GET.get('selected_facets', '')
65 self.form.selected_facets_get = self.request.GET.getlist(
66 'selected_facets', [])
67 return super(AldrynSearchView, self).get(request, *args, **kwargs)
68
69 def get_queryset(self):
70 self.queryset = self.form.search()
71 if not self.request.user.is_authenticated():
72 self.queryset = self.queryset.exclude(login_required=True)
73 self.facet_counts = self.queryset.facet_counts()
74 return self.queryset.order_by('-date_pub')
75
76 def get_context_data(self, **kwargs):
77 context = super(AldrynSearchView, self).get_context_data(**kwargs)
78
79 context['form'] = self.form
80 context['facets'] = self.facet_counts
81 context['selected_facets'] = self.request.GET.getlist(
82 'selected_facets', [])
83 if self.object_list.query.backend.include_spelling:
84 context['suggestion'] = self.form.get_suggestion()
85 return context