Cc L Cc L - 4 months ago 37x
Python Question

UnboundLocalError at /blog/search/ local variable 'cd' referenced before assignment

I am trying to set up django-haystack with solr,,,but I just keep get the error:

UnboundLocalError at /blog/search/ local variable 'cd' referenced
before assignment

I think might be my

something wrong,,,.
my app name "blog",,and there are already several blogs on that
enter image description here

after I add core blog there shows 8 docs

enter image description here

here is my

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'e8m%vu0d&_0o-u*0@^*oh-2k4+j8_$c@qdj@)p353s%5p)2bx^'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True



# Application definition



ROOT_URLCONF = 'mysite.urls'

'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'context_processors': [

WSGI_APPLICATION = 'mysite.wsgi.application'

# Database

'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),

# Internationalization



USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)

STATIC_URL = '/static/'

'default': {
'ENGINE': 'haystack.backends.solr_backend.SolrEngine',
'URL': ''

I have put schema in schema.xml

enter image description here


from django import forms
from .models import Comment

class EmailPostForm(forms.Form):
name = forms.CharField(max_length=25)
email = forms.EmailField()
to = forms.EmailField()
comments = forms.CharField(required=False, widget=forms.Textarea)

class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ('name', 'email', 'body')

class SearchForm(forms.Form):
query = forms.CharField()

my (guess something wrong here??)

from django.shortcuts import render, get_object_or_404
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.views.generic import ListView
from django.core.mail import send_mail
from django.db.models import Count

from taggit.models import Tag

from .models import Post, Comment
from .forms import EmailPostForm, CommentForm, SearchForm
from haystack.query import SearchQuerySet


def post_search(request):
form = SearchForm()
if 'query' in request.GET:
form = SearchForm(request.GET)
if form.is_valid():
cd = form.cleaned_data
results = SearchQuerySet().models(Post).filter(content=cd['query']).load_all()
# count total results
total_results = results.count()
return render(request, 'blog/post/search.html', {'form': form,
'cd': cd,
'results': results,
'total_results': total_results})



{% extends "blog/base.html" %}

{% block title %}Search{% endblock %}

{% block content %}
{% if "query" in request.GET %}
<h1>Posts containing "{{ cd.query }}"</h1>
<h3>Found {{ total_results }} result{{ total_results|pluralize }}</h3>
{% for result in results %}
{% with post=result.object %}
<h4><a href="{{ post.get_absolute_url }}">{{ post.title }}</a></h4>
{{ post.body|truncatewords:5 }}
{% endwith %}
{% empty %}
<p>There are no results for your query.</p>
{% endfor %}
<p><a href="{% url "blog:post_search" %}">Search again</a></p>
{% else %}
<h1>Search for posts</h1>
<form action="." method="get">
{{ form.as_p }}
<input type="submit" value="Search">
{% endif %}
{% endblock %}

from django.conf.urls import url
from . import views
from .feeds import LatestPostsFeed

urlpatterns = [
url(r'^search/$', views.post_search, name='post_search'),

when I click the blog/search it just show the error

enter image description here

error message


Request Method: GET
Request URL:

Django Version: 1.8.8
Python Version: 3.4.4
Installed Applications:
Installed Middleware:

File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/django/core/handlers/" in get_response
132. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/korekyourin/books/djexample/mysite/blog/" in post_search
112. 'cd': cd,

Exception Type: UnboundLocalError at /blog/search/
Exception Value: local variable 'cd' referenced before assignment


In your post_search view you're defining cd only if the form.is_valid().

When the GET request doesn't contains the query variable, you don't have the cd variable, that's why the error is happening.

Try to indent the return render() to the is_valid() conditional.