Python:" name' cd'没有定义"

时间:2016-03-22 02:25:20

标签: python

嗯,这是代码:

def post_search(request):
    global cd,results,total_results
    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})

发现错误打击: name 'cd' is not defined

我定义了' cd'怎么出现这个错误?

1 个答案:

答案 0 :(得分:0)

仅当cd参数在GET请求中可用且表单有效时,才会声明变量query

要解决此问题,请将cd在top上声明为任何默认值。例如)

cd = {}
if 'query' in request.GET:

现在如果没有重新分配cd,你将有一个空的dict,它将作为cleaning_data传递给模板