python - 我不明白为什么我会收到 unboundLocalError

标签 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})

搜索.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 %}

最佳答案

问题是您尝试返回包含 cdresultstotal_results 的上下文字典,即使您的 if 子句不满足。您应该修复缩进:

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

关于python - 我不明白为什么我会收到 unboundLocalError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35600355/

相关文章:

python - Mac OS 上的 pybluez 安装错误

python - 如何在 Python 2.7 中编写 unicode csv

python - Reportlab 的网格看起来完全不正常

Python:来自数组的随机矩阵

Django 休息框架。 raise_exception=真

python - [Microsoft][ODBC Driver 17 for SQL Server]登录超时已过期 (0) (SQLDriverConnect)')

python - Django:使用用户作为外键保存表单

python - 我可以从不同的目录运行 django 测试 (manage.py) 吗?

django - 多语言 django cms 站点 : seo friendlier home pages (redirects)

python - django 中的身份验证