不久前,我开始用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网站代码面板。别在意。
问题是压痕
对于以下对象的python不同:
^{pr2}$您应该确保使用空格进行缩进,python建议使用4个空格而不是制表符
更新:
问题在于URL:
更改为:
这是因为url/new/与regexp匹配
这个错误听起来像是在调用
view_post
视图函数。你确定你的urlpatterns是正确的吗?或者两个URL正则表达式都可以指向view_post
。在在
view_post
中,如果查询没有找到任何项,那么只在for循环中设置的变量post
将不会被设置,render_to_response
中对它的引用将引发UnboundLocalError
。在可以通过在循环之前将post设置为None来避免这种情况。在
您可以使用以下更简单的函数了解UnboundLocalError发生的原因:
^{pr2}$(显然,您不会真正像这样实现
first_element
,但这说明了正在发生的事情。) 如果使用非空列表调用first_element
,它将按预期工作:但如果使用空列表调用它,则结果从未绑定,因此将得到错误:
相关问题 更多 >
编程相关推荐