bgneal@415: """
bgneal@415: This module contains custom code to tailor the Haystack search application to
bgneal@415: our needs.
bgneal@415: 
bgneal@415: """
bgneal@415: import urllib
bgneal@415: 
bgneal@415: from django import forms
bgneal@415: from haystack.views import SearchView
bgneal@415: from haystack.forms import ModelSearchForm
bgneal@415: 
bgneal@415: 
bgneal@415: MODEL_CHOICES = (
bgneal@415:     ('forums.topic', 'Forum Topics'),
bgneal@415:     ('forums.post', 'Forum Posts'),
bgneal@415:     ('news.story', 'News Stories'),
bgneal@415:     ('bio.userprofile', 'User Profiles'),
bgneal@415:     ('weblinks.link', 'Links'),
bgneal@415:     ('downloads.download', 'Downloads'),
bgneal@415:     ('podcast.item', 'Podcasts'),
bgneal@415:     ('ygroup.post', 'Yahoo Group Archives'),
bgneal@415: )
bgneal@415: 
bgneal@415: 
bgneal@415: class CustomModelSearchForm(ModelSearchForm):
bgneal@415:     """
bgneal@415:     This customized ModelSearchForm allows us to explictly label and order
bgneal@415:     the model choices.
bgneal@415: 
bgneal@415:     """
bgneal@415:     q = forms.CharField(required=False, label='',
bgneal@415:             widget=forms.TextInput(attrs={'class': 'text', 'size': 48}))
bgneal@415: 
bgneal@415:     def __init__(self, *args, **kwargs):
bgneal@415:         super(CustomModelSearchForm, self).__init__(*args, **kwargs)
bgneal@415:         self.fields['models'] = forms.MultipleChoiceField(choices=MODEL_CHOICES,
bgneal@415:                 label='', widget=forms.CheckboxSelectMultiple)
bgneal@415: 
bgneal@415: 
bgneal@415: class ModelSearchView(SearchView):
bgneal@415:     """
bgneal@415:     This custom search view puts an extra value in the template context named
bgneal@415:     search_parms. search_parms will contain the search term q plus any models
bgneal@415:     arguments all as a urlencoded string. This is useful for generating
bgneal@415:     pagination links in the template.
bgneal@415: 
bgneal@415:     """
bgneal@415:     def search_params(self):
bgneal@415:         """
bgneal@415:         Return the q and models search parameters as a urlencoded string if the
bgneal@415:         form is valid. An empty string is returned if the form is not valid.
bgneal@415: 
bgneal@415:         """
bgneal@415:         if self.form.is_valid():
bgneal@415:             q = self.form.cleaned_data['q']
bgneal@415:             models = self.form.cleaned_data['models']
bgneal@415: 
bgneal@415:             params = [('q', q)]
bgneal@415:             params.extend([('models', model) for model in models])
bgneal@415:             return urllib.urlencode(params)
bgneal@415: 
bgneal@415:         return ''
bgneal@415: 
bgneal@415:     def extra_context(self):
bgneal@415:         return {'search_params': self.search_params() }