Search code examples
django-haystacksearch-form

Cannot load Haystack custom form


I want to build a custom search form. Below is my code. My app is called "viewer". I keep getting a "NameError at /viewer/search/...name 'CustomSearchForm' is not defined". Please help. I know it is a simple error somewhere.

From viewer/urls.py:

from django.conf.urls import *

from viewer import views, forms
from haystack.views import SearchView

urlpatterns = patterns('',
    #viewer urls
    ...
    url(r'^search/$', SearchView(form_class=CustomSearchForm), name='haystack_search')
)

From viewer/forms.py:

from django import forms
from haystack.forms import ModelSearchForm
from haystack.query import SearchQuerySet

class CustomSearchForm(ModelSearchForm):
    ...

Solution

  • Here is the solution I found, using a different approach:

    urls.py:

    url(r'^search/', 'viewer.views.search'),
    

    views.py:

    def search(request):
        from .forms import CustomSearchForm
        form = CustomSearchForm(request.GET)
        searchresults = form.search()
        return render(request, 'viewer/search.html', {'form' : form})
    

    in viewer/search.html:

    {% extends 'base.html' %}
    
    {% block content %}
    <form type="get" action=".">
        {{form}}
        <button type="submit">Search</button>
    </form>
    {% endblock %}