Django Haystack自定义搜索表单

时间:2016-11-04 13:24:08

标签: python django django-forms django-views django-haystack

我有一个基本的django-haystack SearchForm工作正常,但现在我正在尝试创建一个自定义搜索表单,其中包含一些额外的字段可供过滤。

我已经关注创建自定义表单和视图的Haystack文档了,但是当我尝试查看表单时,我只能得到错误:

ValueError at /search/calibration/

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

不应该基于SearchForm来处理返回HttpResponse对象吗?

forms.py

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

views.py

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

urls.py

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

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

2 个答案:

答案 0 :(得分:2)

Haystack的SearchView是基于类的视图,添加urls条目时必须调用.as_view()类方法。

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

答案 1 :(得分:2)

这对我有帮助。

"去掉search.html模板上的"page"前缀就成功了,是一个很好的临时解决方案。然而,到了对结果进行分页的时候就成了一个问题。所以环顾四周,解决方案是使用“page_obj”前缀而不是“page”,一切都按预期工作。似乎问题是 haystack-tutorial 假设页面对象称为“page”,而某些版本的 django 称为“page_obj”?我肯定有更好的答案 - 我只是报告我有限的发现。”

看到这个:Django-Haystack returns no results in search form