我无法理解为什么我得到unboundLocalError

时间:2016-02-24 11:04:49

标签: python django

我使用的是django 1.8和python 2.7,但我一直在使用unbounLocalError。看起来我的views.py中的代码都可以。但是在分配之前它会继续引用局部变量'cd'。如果有人能提供解决方案我会很高兴

def post_search(request):
    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})

search.html

{% extends "blog/base.html" %}

{% block title %}Search{% endblock %}

{% block content %}
    {% if "query" in request.GET %}
        <h1>Posts containing "{{ cd.query }}"</h1>
        <h3>Found {{ total_results }} result{{     total_results|pluralize }}</h3>
        {% for result in results %}
            {% with post=result.object %}
            <h4><a href="{{ post.get_absolute_url }}">    {{ post.title }}</a></h4>
                {{ post.body|truncatewords:5 }}
            {% endwith %}
        {% empty %}
            <p>There are no results for your query.</p>
        {% endfor %}
        <p><a href="{% url "blog:post_search" %}">Search again</a></p>
    {% else %}
        <h1>Search for posts</h1>
        <form action="." method="get">
            {{ form.as_p }}
            <input type="submit" value="Search">
        </form>
    {% endif %}
{% endblock %}

1 个答案:

答案 0 :(得分:2)

问题是,即使您的cd条款不满意,您也会尝试返回包含resultstotal_resultsif的上下文字典。你应该修改你的缩进:

def post_search(request):
    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()
            # Indent this line:
            return render(request, 'blog/post/search.html', {'form': form,
                                                 'cd': cd,
                                                 'results': results,
                                                 'total_results':  total_results})