wsvincent
wsvincent

Reputation: 207

Override the user query in Haystack

I want the user query in my Django/Haystack app to be sorted in alphabetical order. For example if the user entered "sit" this would be changed to "ist" in the Haystack Search Index.

I believe overriding the default Haystack forms.py will achieve this, but can't get it to work.

#forms.py
from haystack.forms import SearchForm

class WordsSearchForm(SearchForm):

    q_default = forms.CharField(required=False, label=_('Search'),
                            widget=forms.TextInput(attrs={'type': 'search'}))

    q = ''.join(sorted(q_default))

Any suggestions on how to achieve this?

Upvotes: 1

Views: 322

Answers (1)

wsvincent
wsvincent

Reputation: 207

Customizing Haystack is a bit tricky it turns out. To override the user query you need to create a forms.py file, update views.py, and update urls.py.

#forms.py
from haystack.forms import SearchForm

class WordsSearchForm(SearchForm):

def search(self):
    # added the two lines below
    q = self.cleaned_data['q']
    q = ''.join(sorted(q))

    if not self.is_valid():
        return self.no_query_found()

    if not self.cleaned_data.get('q'):
        return self.no_query_found()

    # default is...
    # sqs = self.searchqueryset.auto_query(self.cleaned_data['q'])
    sqs = self.searchqueryset.auto_query(q)

    if self.load_all:
        sqs = sqs.load_all()

    return sqs


# views.py
from haystack.views import SearchView

from .models import [NAME OF YOUR MODEL]
from .forms import WordsSearchForm

class MySearchView(SearchView):

    form = WordsSearchForm


#urls.py
from haystack.views import SearchView, search_view_factory
from scrabble.views import MySearchView
from APP.forms import WordsSearchForm

urlpatterns = patterns('',
    # replace default haystack url
    # url(r'^search/', include('haystack.urls')),

      url(r'^search/$', search_view_factory(
                       form_class=WordsSearchForm
                       ), name='haystack_search'),
)

Upvotes: 1

Related Questions