Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6472587
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T06:21:47+00:00 2026-05-25T06:21:47+00:00

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

  • 0

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/views.py" in search
 40.    if query and len(query) > 2:

Exception Type: UnboundLocalError at /search/
Exception Value: local variable 'query' referenced before assignment
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-25T06:21:48+00:00Added an answer on May 25, 2026 at 6:21 am

    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?
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have this page which loads quotes. It has a search form wherein if
We have a page of search results which the user can hit in several
I'm using codeigniter for this project. I have a search form and search form
I basically have this web page where you can narrow your search results by
I'm using he following code the call a CFC which returns auto-suggest results through
I have a typical search facility in my app which returns a list of
I have a page with a search form, and when submitted, the form action
I have a login.jsp page which contains a login form. Once logged in the
I have this sphinx search engine that I use through Zend using sphinxapi.php .
I have a page where search resuts are shown both in a grid and

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.