local variable context_dict referenced before assignment
Question: I am making a django app .According to me everything is in views.py but when i
run the server it generates an error `local variable 'state' referenced before
assignment`

I have made the context_dict variable in the above view but then too it is
generating error.

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
    


Answer: That's pretty obvious, your code went to the `except` block, but
`context_dict` is only defined in `try` block, so when you use it in your
`render` function, it's not defined. The quickest fix is to define
`context_dict` as empty dict at the beginning of the function so that it's
always there when you return it.

