UnboundLocalError:赋值前引用的本地“类别”变量

时间:2014-02-18 17:44:56

标签: python django django-views

我通过做一个小型网络应用程序来学习django,我现在跟随http://www.tangowithdjango.com/book/chapters/models_templates.html第6章

views.py

   category_list = Category.objects.order_by('-likes')[:5]  
   def index(request):
   context = RequestContext(request)
   global category_list
   context_dict = {'categories': category_list}

    for category in category_list:
    category.url = category.name.replace(' ', '_')
    return render_to_response('rango/index.html', context_dict, context)


    def category(request, category_name_url):

     context = RequestContext(request)
     category_name = category_name_url.replace('_', ' ')
     context_dict = {'category_name': category_name}

try:

    category = Category.objects.get(name=category_name)
    pages = Page.objects.filter(category=category)
    context_dict['pages'] = pages
    context_dict['category'] = category

except Category.DoesNotExist:
    pass

return render_to_response('rango/category.html', context_dict, context)

urls.py

url(r'^about/$', views.about, name='about'),
url(r'^category/(?P<category_name_url>\w+)/$', views.category, name='category'),) 
    Environment:


Request Method: GET
Request URL: http://'localhost:8080'/rango/catgeory/python/

Django Version: 1.6.1
Python Version: 2.7.3
Installed Applications:
('django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'rango')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware')


Traceback:
File "C:\python27\lib\site-packages\django\core\handlers\base.py" in get_response
  114.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\User\Documents\tango\rango\views.py" in catgeory
  34.     except  catgeory.DoesNotExist:  

Exception Type: UnboundLocalError at /rango/catgeory/python/
Exception Value: local variable 'catgeory' referenced before assignment

实际上category_name_url=u'python'这对python有好处,但我不确定u之前的值和我正在使用eclipse

1 个答案:

答案 0 :(得分:1)

该回溯与您的代码不符。回溯显示Category.DoesNotExist时,视图代码显示category.DoesNotExist。前者起作用是因为定义了类Category。后者不起作用,因为category引发异常时Category.objects.get()尚不存在。

如果上面的视图代码是准确的,那么你还有其他问题会导致执行过时的代码。