您好我有一个搜索结果页面,使用此视图从数据库返回查询:
def search(request):
show_results = False
# check if POST
if 'q' in request.POST:
query = request.POST['q'].strip()
# check if GET (paginated)
if 'q' in request.GET:
query = request.GET['q'].strip()
# check if query length is more than 2 characters and proceed
if query and len(query) > 2:
# if there is a query string show results (as opposed to arriving without any POST/GET
show_results = True
keywords = query.split()
q = Q()
for keyword in keywords:
q = q & (Q(title__icontains=keyword) | (Q(keywords__icontains=keyword)))
query_set = Article.objects.filter(q)
# create a new paginator instance with items-per-page
paginator = Paginator(query_set, 10)
# get the page number from a get param if param is blank then set page to 1
page = int(request.GET.get('page', '1'))
# grab the current page from the paginator...
items = paginator.page(page)
# update search counter with term
try:
term = Search.objects.get(term=query)
except Search.DoesNotExist:
# if not already in db, then add query
term = Search(term=query)
term.counter += 1
term.last_search = datetime.now()
term.save()
elif len(query) <= 2:
short_string = True
else:
pass
#render the template and pass the contacts page into the template
return render_to_response('search_results.html',
locals(), context_instance=RequestContext(request))
和模板:
{% load i18n %}
<form action="/i18n/setlang/" name=postlink method="post">
<ul class="lang">
<li class="lang" style="color:gray">
{% for lang in LANGUAGES %}
{% if lang.0 != LANGUAGE_CODE %}
<input type="hidden" name="language" value="{{ lang.0 }}">
<a href=# onclick="submitPostLink()">{{ lang.1 }}</a>
{% else %}
{{ lang.1 }}
{% endif %}
{% endfor %}
</li></ul>
</form>
除一种情况外,语言切换在所有页面上都能正常工作。当我在搜索结果页面上提交没有返回结果的语言更改数据时(即空查询集),我收到以下错误:
UnboundLocalError at /search/
local variable 'query' referenced before assignment
我想我需要略微调整视图,但我不知道在哪里。任何建议都非常赞赏。
回溯:
traceback: `Environment:
Request Method: GET
Request URL: http://localhost:8000/search/
Django Version: 1.3
Python Version: 2.7.1
Installed Applications:
['django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'journal',
'django.contrib.admin']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.locale.LocaleMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.csrf.CsrfResponseMiddleware')
Traceback:
File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "/home/sam/public_html/django- projects/galapagos_research/../galapagos_research/journal/views.py" in search
40. if query and len(query) > 2:
Exception Type: UnboundLocalError at /search/
Exception Value: local variable 'query' referenced before assignment
答案 0 :(得分:1)
如果query
不在POST或GET中,则您尚未定义q
。由于这是唯一出现此错误的地方,因此您不得传入q
。空QuerySet不会导致此错误。
可以肯定的是,触发错误的行(请追溯 - 请)会有所帮助。
def search(request):
show_results = False
query = None # set default value for query
# check if POST
if 'q' in request.POST:
query = request.POST['q'].strip()
# check if GET (paginated)
if 'q' in request.GET:
query = request.GET['q'].strip()
###########################
# was `query` defined here if 'q' isn't in POST or GET?
###########################
# check if query length is more than 2 characters and proceed
if query and len(query) > 2: # error probably on this line?
答案 1 :(得分:0)
一开始,查询永远不会设置为默认值。
if 'q' in request.POST:
query = request.POST['q'].strip()
# check if GET (paginated)
if 'q' in request.GET:
query = request.GET['q'].strip()
然后在你的elif中,你尝试确定查询的len(),如果'q'不在GET或POST中,那么它在任何地方都没有定义。
elif len(query) <= 2:
short_string = True