Question

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):
    ...
Was it helpful?

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 %} 

OTHER TIPS

Had the same problem but with "NameError at /viewer/search/...name 'SearchForm' is not defined" trying to follow the guide here: http://django-haystack.readthedocs.io/en/v2.6.0/views_and_forms.html

Just upgrading to Django 1.11.0 did the trick for me. Maybe it would work for you too.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top