我正在创建一个django应用程序。据我所知,一切都在views.py中但是当我运行服务器时它会生成一个错误local variable 'state' referenced before assignment
我在上面的视图中创建了context_dict变量,但它也产生了错误。
views.py
from django.shortcuts import render
from .models import States,Colleges
def index(request):
all_states = States.objects.all()
context_dict = {'all_states':all_states}
return render(request,'practise_app/index.html',context_dict)
def college(request,state_slug):
try:
state = States.objects.get(slug = state_slug)
colleges = Colleges.objects.filter(state = state)
context_dict = {'state':state,'colleges':colleges}
except States.DoesNotExist:
pass
return render(request,'practise_app/colleges.html',context_dict)
TRACEBACK:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/madhya-pradesh/
Django Version: 1.8
Python Version: 3.5.1
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'practise_app')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware')
Traceback:
File "C:\Users\sahib navlani\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\handlers\base.py" in get_response
132. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "D:\practise_project\practise_app\views.py" in college
19. return render(request,'practise_app/colleges.html',context_dict)
Exception Type: UnboundLocalError at /madhya-pradesh/
Exception Value: local variable 'context_dict' referenced before assignment
答案 0 :(得分:3)
很明显,您的代码转到except
块,但context_dict
仅在try
块中定义,因此当您在render
函数中使用它时,它没有定义。最快的解决方法是将context_dict
定义为函数开头的空字典,以便在返回时始终存在。