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