调用其他函数时发生Python Django UnboundLocalError

2024-09-28 05:16:23 发布

您现在位置:Python中文网/ 问答频道 /正文

不久前,我开始用Django编程Python。有时候我会犯奇怪的错误,却不知道为什么。所以,让我们从这些错误中的一个开始。在

我有两个功能的视图。示例:

def view_post(request, slug):
    """
    Shows a single post
    """
    posts = Post.objects(slug = slug).limit(1)
    for items in posts:
        post = items

    cssClasses = css_class_converter({ _css_class_editable })

    context = RequestContext(request)
    return render_to_response("single.html", { 'post': post, 'class': cssClasses }, context)

def new_post(request):
    '''
    Opens a blank page for creating a new post
    '''

    post = Post()
    cssClasses = css_class_converter({ _css_class_editable, _css_class_new })
    context = RequestContext(request)
    return render_to_response("single.html", {'post': post, 'new': True }, context)

然后用我的URLconf给他们打电话。调用view_post函数可以正常工作,没有错误。在

^{pr2}$

但是调用新的\u post函数会在第39行的UnboundLocalError异常中运行:“赋值前引用的局部变量'post'。第39行是view函数的render_to_响应,而不是新函数。在

那么,为什么我对新函数的调用会在我的视图函数中抛出错误?真的,我不知道。我是从C来的,所以我确信我没有得到一些特殊的Python规则,这会使我的代码出错。在

更新:两个函数的缩进不正确,因为stackoverflow.com网站代码面板。别在意。

enter image description here


Tags: to函数view视图newrequest错误context
2条回答

问题是压痕

def view(request):
    ...
    def new(request):
        ...

对于以下对象的python不同:

^{pr2}$

您应该确保使用空格进行缩进,python建议使用4个空格而不是制表符

更新:

问题在于URL:

url(r'^$', views.index),
url(r'^(?P<slug>[^\.]+)', 'view_post', name='view_blog_post'),
url(r'^new/$', 'new_post', name='new_blog_post'),

更改为:

url(r'^$', views.index),
url(r'^new/$', 'new_post', name='new_blog_post'),
url(r'^(?P<slug>[^\.]+)', 'view_post', name='view_blog_post'),

这是因为url/new/与regexp匹配

r'^(?P<slug>[^\.]+)'

这个错误听起来像是在调用view_post视图函数。你确定你的urlpatterns是正确的吗?或者两个URL正则表达式都可以指向view_post。在

view_post中,如果查询没有找到任何项,那么只在for循环中设置的变量post将不会被设置,render_to_response中对它的引用将引发UnboundLocalError。在

可以通过在循环之前将post设置为None来避免这种情况。在

def view_post(request, slug):
        """
        Shows a single post
        """
        posts = Post.objects(slug = slug).limit(1)
        post = None   # Ensure post is bound even if there are no posts matching slug
        for items in posts:
            post = items

        cssClasses = css_class_converter({ _css_class_editable })

        context = RequestContext(request)
        return render_to_response("single.html", { 'post': post, 'class': cssClasses }, context)

您可以使用以下更简单的函数了解UnboundLocalError发生的原因:

^{pr2}$

(显然,您不会真正像这样实现first_element,但这说明了正在发生的事情。) 如果使用非空列表调用first_element,它将按预期工作:

>>> first_element([2, 3, 4])
2

但如果使用空列表调用它,则结果从未绑定,因此将得到错误:

>>> first_element([])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 5, in first_element
UnboundLocalError: local variable 'result' referenced before assignment

相关问题 更多 >

    热门问题