gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 04:05:56 25 4
gpt4 key购买 nike

我正在使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com