分配前引用的 /blog/search/ 局部变量 'cd' 处的 UnboundLocalError

Posted

技术标签:

【中文标题】分配前引用的 /blog/search/ 局部变量 \'cd\' 处的 UnboundLocalError【英文标题】:UnboundLocalError at /blog/search/ local variable 'cd' referenced before assignment分配前引用的 /blog/search/ 局部变量 'cd' 处的 UnboundLocalError 【发布时间】:2016-09-25 17:35:59 【问题描述】:

我正在尝试使用 solr 设置 django-haystack,但是我一直收到错误消息:

UnboundLocalError 在 /blog/search/ 局部变量 'cd' 被引用 分配前

我想可能是我的

views.py

出了点问题,,,。 我的应用名称为“博客”,并且已经有几个博客

在我添加核心博客后显示 8 个文档

这是我的

settings.py

# 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 https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/

# 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

ALLOWED_HOSTS = []

SITE_ID = 1

# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'blog',
    'taggit',
    'django.contrib.sites',
    'django.contrib.sitemaps',
    'haystack',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',
)

ROOT_URLCONF = 'mysite.urls'

TEMPLATES = [
    
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': 
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        ,
    ,
]

WSGI_APPLICATION = 'mysite.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases

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



# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, javascript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/

STATIC_URL = '/static/'



HAYSTACK_CONNECTIONS = 
    'default': 
        'ENGINE': 'haystack.backends.solr_backend.SolrEngine',
        'URL': 'http://127.0.0.1:8983/solr/blog'
    ,

我已将架构放入 schema.xml

我的

forms.py

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()

我的(猜猜这里有什么问题??)

views.py

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)

我的

搜索.html

% 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">
        </form>
    % endif %
% endblock %

urls.py

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


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

当我点击博客/搜索时,它只会显示错误

错误信息

Environment:


Request Method: GET
Request URL: http://127.0.0.1:8000/blog/search/

Django Version: 1.8.8
Python Version: 3.4.4
Installed Applications:
('django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'blog',
 'taggit',
 'django.contrib.sites',
 'django.contrib.sitemaps',
 'haystack')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'django.middleware.security.SecurityMiddleware')


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

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

【问题讨论】:

【参考方案1】:

首先,感谢安德烈回答我,,,这是我的新

views.py

.......

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)


    return render(request, 'blog/post/search.html', 'form': form,)

【讨论】:

【参考方案2】:

在您的post_search 视图中,您仅在form.is_valid() 时才定义cd

当 GET 请求不包含 query 变量时,您没有 cd 变量,这就是发生错误的原因。

尝试将 return render() 缩进到 is_valid() 条件。

【讨论】:

谢谢,在我将 return render() 缩进到 is_valid() 条件之后。然后输入:form = SearchForm() return render(request, 'blog/post/search.html' , 'form': form,) 在is_valid()条件之外,,,它可以工作

以上是关于分配前引用的 /blog/search/ 局部变量 'cd' 处的 UnboundLocalError的主要内容,如果未能解决你的问题,请参考以下文章

UnboundLocalError:分配前引用的局部变量“公会”

错误:“分配前引用了局部变量‘myData’”

分配前引用的 Django 局部变量“表单”

Python 3:UnboundLocalError:分配前引用的局部变量[重复]

机器人框架:UnboundLocalError:分配前引用的局部变量“cellValue”

Django:UnboundLocalError:分配前引用的局部变量“公司”