TimB TimB - 2 months ago 61
Python Question

Django Haystack Custom Search Form

I've got a basic django-haystack SearchForm working OK, but now I'm trying to create a custom search form that includes a couple of extra fields to filter on.

I've followed the Haystack documentation on creating custom forms and views, but when I try to view the form I can only get the error:

ValueError at /search/calibration/

The view assetregister.views.calibration_search didn't return an HttpResponse object. It returned None instead.

Shouldn't basing this on SearchForm take care of returning a HttpResponse object?


from django import forms
from haystack.forms import SearchForm

class CalibrationSearch(SearchForm):
calibration_due_before = forms.DateField(required=False)
calibration_due_after = forms.DateField(required=False)

def search(self):
#First we need to store SearchQuerySet recieved after / from any other processing that's going on
sqs = super(CalibrationSearch, self).search()

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

#check to see if any date filters used, if so apply filter
if self.cleaned_data['calibration_due_before']:
sqs = sqs.filter(calibration_date_next__lte=self.cleaned_data['calibration_due_before'])

if self.cleaned_data['calibration_due_after']:
sqs = sqs.filter(calibration_date_next__gte=self.cleaned_data['calibration_due_after'])

return sqs


from .forms import CalibrationSearch
from haystack.generic_views import SearchView
from haystack.query import SearchQuerySet

def calibration_search(SearchView):
template_name = 'search/search.html'
form_class = CalibrationSearch
queryset = SearchQuerySet().filter(requires_calibration=True)

def get_queryset(self):
queryset = super(calibration_search, self).get_queryset()
return queryset


from django.conf.urls import include, url
from . import views

urlpatterns = [
url(r'^search/calibration/', views.calibration_search, name='calibration_search'),


Haystack's SearchView is a class based view, you have to call .as_view() class method when adding a urls entry.

url(r'^search/calibration/', views.calibration_search.as_view(), name='calibration_search'),