开发者

Django - language switching with query data

Hi I have a search results page which returns queries form the database using this view:

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

and the template:

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

The language switching works fine on all pages except one case. When I submit the language change data on the search results page where no results have been returned (i.e. empty queryset), I get the following error:

UnboundLocalError at /search/
local variable 'query' referenced before assignment

I think I need to tweak the view slightly, but I'm not sure where. Any suggestions much appreciated.

Traceback:

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/view开发者_运维百科s.py" in search
 40.    if query and len(query) > 2:

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


You haven't defined query if q isn't in POST or GET. Since that's the only place where this error would appear, you must not be passing in q. An empty QuerySet wouldn't cause this error.

To be sure, it would help to have the line that triggered the error (the traceback - please).

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?


At the start, query is never set to a default.

if 'q' in request.POST:
    query = request.POST['q'].strip()
# check if GET (paginated)
if 'q' in request.GET:
    query = request.GET['q'].strip()

Then in your elif, you try to determine the len() of query which isn't defined anywhere yet if 'q' is not in GET or POST.

elif len(query) <= 2:
    short_string = True
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜