2014-03-19 48 views
0

請幫助我,我有這樣的錯誤:關於Django的searchname

Exception Type: UnboundLocalError Exception Value: local variable 'query_string' referenced before assignment

這是我的views.py:

def normalize_query(query_string, 
        findterms=re.compile(r'"([^"]+)"|(\S+)').findall, 
        normspace=re.compile(r'\s{2,}').sub): 

    return [normspace(' ', (t[0] or t[1]).strip()) for t in findterms(query_string)] 

def get_query(query_string, search_fields): 

    query = None # Query to search for every search term   
    terms = normalize_query(query_string) 
    for term in terms: 
     or_query = None # Query to search for a given term in each field 
     for field_name in search_fields: 
      q = Q(**{"%s__icontains" % field_name: term}) 
      if or_query is None: 
       or_query = q 
      else: 
       or_query = or_query | q 
     if query is None: 
      query = or_query 
     else: 
      query = query & or_query 
    return query 

@login_required  
def search_name(request): 
    form = ArticleForm(request.POST) 
    if ('q' in request.POST) and request.POST['q'].strip(): 
     query_string = request.POST['q'] 
     entry_query = get_query(query_string, ['user_name', 'company',]) 
     articles = User.objects.filter(entry_query).order_by('-pub_date') 
    else: 
     index = User.objects.all().order_by('-pub_date') 

    return render_to_response('index.html', 
          { 'query_string': query_string, 'index': index }, 
         context_instance=RequestContext(request)) 

的index.html:

<form action="" method="POST"> 
<label for="id_q"></label> 
<input name="q" id="id_q" type="text"> 
<p><input type="submit" value="Search" class="button"></p></form> 

回答

1

如果('q' in request.POST) and request.POST['q'].strip()評估板到Falsequery_string變量保持未定義。要解決這個問題

一種方法是if語句之前初始化變量:

@login_required  
def search_name(request): 
    form = ArticleForm(request.POST) 
    query_string = None 
    if ('q' in request.POST) and request.POST['q'].strip(): 
    ... 

希望有所幫助。

+0

非常感謝!這很有幫助 – vigor100

+0

謝謝!,當然 – vigor100