comparison gpp/custom_search.py @ 415:d4d167876c25

Fixing #205; search result pagination wasn't including models. Created a custom model search form so that the query term and model selections would persist across pages.
author Brian Neal <bgneal@gmail.com>
date Sun, 10 Apr 2011 00:32:14 +0000
parents
children 524fd1b3919a
comparison
equal deleted inserted replaced
414:b1f939b1fb01 415:d4d167876c25
1 """
2 This module contains custom code to tailor the Haystack search application to
3 our needs.
4
5 """
6 import urllib
7
8 from django import forms
9 from haystack.views import SearchView
10 from haystack.forms import ModelSearchForm
11
12
13 MODEL_CHOICES = (
14 ('forums.topic', 'Forum Topics'),
15 ('forums.post', 'Forum Posts'),
16 ('news.story', 'News Stories'),
17 ('bio.userprofile', 'User Profiles'),
18 ('weblinks.link', 'Links'),
19 ('downloads.download', 'Downloads'),
20 ('podcast.item', 'Podcasts'),
21 ('ygroup.post', 'Yahoo Group Archives'),
22 )
23
24
25 class CustomModelSearchForm(ModelSearchForm):
26 """
27 This customized ModelSearchForm allows us to explictly label and order
28 the model choices.
29
30 """
31 q = forms.CharField(required=False, label='',
32 widget=forms.TextInput(attrs={'class': 'text', 'size': 48}))
33
34 def __init__(self, *args, **kwargs):
35 super(CustomModelSearchForm, self).__init__(*args, **kwargs)
36 self.fields['models'] = forms.MultipleChoiceField(choices=MODEL_CHOICES,
37 label='', widget=forms.CheckboxSelectMultiple)
38
39
40 class ModelSearchView(SearchView):
41 """
42 This custom search view puts an extra value in the template context named
43 search_parms. search_parms will contain the search term q plus any models
44 arguments all as a urlencoded string. This is useful for generating
45 pagination links in the template.
46
47 """
48 def search_params(self):
49 """
50 Return the q and models search parameters as a urlencoded string if the
51 form is valid. An empty string is returned if the form is not valid.
52
53 """
54 if self.form.is_valid():
55 q = self.form.cleaned_data['q']
56 models = self.form.cleaned_data['models']
57
58 params = [('q', q)]
59 params.extend([('models', model) for model in models])
60 return urllib.urlencode(params)
61
62 return ''
63
64 def extra_context(self):
65 return {'search_params': self.search_params() }