UnboundLocalError-赋值前引用的局部变量 - Django

发布于 2024-11-30 10:29:22 字数 2609 浏览 0 评论 0原文

这周你们帮了我很多忙,真是太棒了。希望你们能帮我解决这个问题。我尝试查看网站上有关此类错误的其他帖子,但没有一个真正帮助我解决问题。基本上,我在一页上提交一个表单,并且 POST 数据将转到生成它的同一视图。我想在发送 POST 数据后重定向到其他页面,但收到此错误。

def test(request):
    if request.method == 'POST':
        form = SubmitForm(request.POST) # A form bound to the POST data
        if form.is_valid():
            lat = form.cleaned_data['lat'] 
            lng = form.cleaned_data['lng']
            title = form.cleaned_data['title']
            story = form.cleaned_data['story']

            ctxt = {
                    'lat':lat,
                    'lng':lng,
                    'title':title,
                    'story':story,
                    }

            return render_to_response('home.html', ctxt, context_instance=RequestContext(request)) 

    else:

        import datetime
        now = datetime.datetime.now()
        form = SubmitForm()
        latest_marks = Marker.objects.all().order_by('-submitted')[0:10]

        ctxt = {
                'marks':latest_marks,
                'now':now.date(),
                'form': form,
                }
    return render_to_response('test.html', ctxt, context_instance=RequestContext(request)) 

我得到的错误是

local variable 'ctxt' referenced before assignment

回溯是

Environment:


Request Method: POST
Request URL: http://localhost:8000/test/

Django Version: 1.3
Python Version: 2.6.5
Installed Applications:
['django.contrib.staticfiles',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.admin',
 'userena',
 'guardian',
 'easy_thumbnails',
 'south',
 'database',
 'accounts',
 'socialregistration']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'userena.middleware.UserenaLocaleMiddleware',
 'socialregistration.middleware.FacebookMiddleware')


Traceback:
File "/home/wluw/dev/chicagomap/lib/python2.6/site-packages/Django-1.3-py2.6.egg/django/core/handlers/base.py" in get_response
  111.                         response = callback(request, *callback_args, **callback_kwargs)
File "/home/wluw/dev/chicagomap/chicagomap/../chicagomap/database/views.py" in test
  58.     return render_to_response('test.html', ctxt, context_instance=RequestContext(request)) 

Exception Type: UnboundLocalError at /test/
Exception Value: local variable 'ctxt' referenced before assignment

任何帮助将不胜感激。谢谢。

You guys have helped me out so much this week it has been awesome.Hopefully you can help me out with this one. I tried looking at the other posts on the site about this type of error, but none of them really helped me out. Basically I am submitting a form on one page and the POST data is going to the same view that it was generated with. I want to redirect to an other page after the POST data is sent, but I get this error.

def test(request):
    if request.method == 'POST':
        form = SubmitForm(request.POST) # A form bound to the POST data
        if form.is_valid():
            lat = form.cleaned_data['lat'] 
            lng = form.cleaned_data['lng']
            title = form.cleaned_data['title']
            story = form.cleaned_data['story']

            ctxt = {
                    'lat':lat,
                    'lng':lng,
                    'title':title,
                    'story':story,
                    }

            return render_to_response('home.html', ctxt, context_instance=RequestContext(request)) 

    else:

        import datetime
        now = datetime.datetime.now()
        form = SubmitForm()
        latest_marks = Marker.objects.all().order_by('-submitted')[0:10]

        ctxt = {
                'marks':latest_marks,
                'now':now.date(),
                'form': form,
                }
    return render_to_response('test.html', ctxt, context_instance=RequestContext(request)) 

The error I get is

local variable 'ctxt' referenced before assignment

And the traceback is

Environment:


Request Method: POST
Request URL: http://localhost:8000/test/

Django Version: 1.3
Python Version: 2.6.5
Installed Applications:
['django.contrib.staticfiles',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.admin',
 'userena',
 'guardian',
 'easy_thumbnails',
 'south',
 'database',
 'accounts',
 'socialregistration']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'userena.middleware.UserenaLocaleMiddleware',
 'socialregistration.middleware.FacebookMiddleware')


Traceback:
File "/home/wluw/dev/chicagomap/lib/python2.6/site-packages/Django-1.3-py2.6.egg/django/core/handlers/base.py" in get_response
  111.                         response = callback(request, *callback_args, **callback_kwargs)
File "/home/wluw/dev/chicagomap/chicagomap/../chicagomap/database/views.py" in test
  58.     return render_to_response('test.html', ctxt, context_instance=RequestContext(request)) 

Exception Type: UnboundLocalError at /test/
Exception Value: local variable 'ctxt' referenced before assignment

Any help would be greatly appreciated. Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

抱着落日 2024-12-07 10:29:22

发生这种情况是因为 request.method == 'POST' 为 True(第一个条件通过),但 form.is_valid() 为 False(第二个嵌套条件失败),这意味着else 运行后的最终返回,但 ctxt 未定义。

也许您希望将最终的返回缩进为 else 子句的一部分?

This is happening because request.method == 'POST' is True (first condition passes) but form.is_valid() is False (second nested condition fails), which means the final return after the else is run but ctxt is not defined.

Perhaps you intended that final return to be indented as a part of the else clause?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文