我一直收到以下错误"本地变量' total_results'在转让前引用"

时间:2016-03-18 18:52:17

标签: python django

我是django和python的新手,我正在关注django教程并且我一直收到以下错误

UnboundLocalError at /blog/search/
local variable 'total_results' referenced before assignment

继承我的代码

 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()
        template = 'blog/post/search.html'
        context = {
           'form': form,
           'cd': cd,
           'results': results,
           'total_results': total_results
        }
        return render(request, template, context)

我也尝试过这样的原因,因为教程是如何实现的

 return render(request, template, {
    'form': form,
    'cd': cd,
    'results': results,
    'total_results': total_results
  })

但这也没有用

我理解错误消息的内容,但这是本教程的内容。使这项工作的正确语法是什么。欢迎所有指导

编辑:这是模板代码

   {% 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 %}

4 个答案:

答案 0 :(得分:3)

如果没有传递query GET参数,或者表单无法通过验证 - 在这种情况下,total_resultsresults将不会被定义。您需要为该情况提供默认值,例如:

def post_search(request):
    results = []
    total_results = 0

    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()
    template = 'blog/post/search.html'
    context = {
       'form': form,
       'cd': cd,
       'results': results,
       'total_results': total_results
    }
    return render(request, template, context)

或者,抛出特定的&#34;验证&#34;如果没有query参数或表单无效,则出错。

答案 1 :(得分:3)

        2
    1       3
 0     4

Python指出如果&#39; if&#39;会发生什么?条件失败,你仍然在使用变量&total;'结果&#39;在上下文中。因此,根据需要将其初始化为0或无。类似于&#39;结果&#39;变量也是如此。

EDIT1:由于我并不完全知道你想要达到的目标,我最好的猜测就是使用这段代码。

EDIT2:模板代码更改

def post_search(request):
    results = []  # or None
    total_results = 0  # or None
    form = SearchForm(request.GET or None)
    if 'query' in 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()
            template = 'blog/post/search.html'
            context = {
               'form': form,
               'cd': cd,
               'results': results,
               'total_results': total_results
                    }
               return render(request, template, context)
       else:
            return render(request, 'blog/post/search.html', {'form': form,})
    else:
       return render(request, 'blog/post/search.html', {'form': form,})

答案 2 :(得分:1)

我已经阅读了同一本书,并注意到该特定视图存在同样的问题。这是我在视图中的解决方案。我按原样离开了模板(在书中):

def post_search(request):
    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()
            total_results = results.count()
            context = {'form':form, 'cd':cd, 'results':results, 'total_results':total_results}
            return render (request, 'blog/post/search.html', context)
    else:
        form = SearchForm()
        context = {'form':form}
        return render (request, 'blog/post/search.html', context)

答案 3 :(得分:1)

有完全相同的问题...下面的代码可以使用

    def post_search(request):
        results = []
        total_results = 0
        cd = None
        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()    
        total_results = results.count()
    return render(request, 'search/search.html', {'form':form,
                                               'cd':cd,
                                               'results':results,
                                               'total_results':total_results,
                                               })

但出于兴趣,您是否也发现post_detail视图产生了类似的错误?用这个版本的代码解决了那个问题

    def post_detail(request, year, month, day, post):


        post = get_object_or_404(Post, slug=post,
                                   status='published',
                                   publish__year=year,
                                   publish__month=month,
                                   publish__day=day)


    #list of active comments for this post
    comments = post.comments.filter(active=True)

    if request.method == 'POST':
        # A comment was posted
        comment_form = CommentForm(data=request.POST)
        if comment_form.is_valid():
            #create comment object but don't save to DB
            new_comment = comment_form.save(commit=False)
            # assitgn comment to post
            new_comment.post = post
            # save the comment to the DB
            new_comment.save()

    else:
        comment_form =CommentForm()





   post_tags_ids = post.tags.values_list('id', flat=True)
   similar_posts =    Post.published.filter(tags__in=post_tags_ids).exclude(id=post.id)
   similar_posts = similar_posts.annotate(same_tags=Count('tags')).order_by('-same_tags','-publish')[:4]


   args = {}
   args['post'] = post 
   args['comment_form']= comment_form
   args['comments'] = comments 
   args['similar_posts'] = similar_posts
   return render(request, 'detail.html', args )