How to Solve Error Message UnboundLocalError: local variable ‘variable’ referenced before assignment in Django

Posted on

This article will show another content which has the relation with the usage of ‘context_processors.py’. It exists as article in this link with the title of ‘How to Solve Error Message models.Model.DoesNotExist: Model matching query does not exist in Django’. The following is the content of the ‘context_processors.py’ :

from loads.models import Assistant

def assistant(request):
    """A context processor to add the logged in member """

    try:
        assistant = Assistant.objects.get(user=request.user)
        return {
            'logged_in_assistant': assistant
        }
    except TypeError:
        # We should redirect really, but for now
        return {
    
        }     

The above source code is a context_processors.py’ file. The main purpose is to be able initialize a variable with the name ‘assistant’. There must be an alignment with the definition exist in the settings.py file. Furthermore, just read the article with the article of ‘How to Load Context Processors in Django Web-based Application’ in this link. It is about knowing how to set or to define the ‘context_processors.py’ file.  So, the following is the content of ‘context_processors.py’ file :

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'loads.context_processors.assistant'
            ],
        },
    },
]

The alignment exist as a variable definition in the above settings.py file configuration. That alignment is a variable with the name of ‘assistant’. It is because in the context_processors.py file, the variable initialization is ‘assistant’. So, every time a template file is being rendered, it will search for the value of ‘assistant’ in the context-processors.py file exist in ‘loads’ folder. But if the variable exist and there is no value available or it is not being initiated, the following error will appear as follows :

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "C:\python-win\myenv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\python-win\myenv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\python-win\myenv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\python-win\app\loads\views.py", line 68, in index
return HttpResponse(template.render(context, request))
File "C:\python-win\myenv\lib\site-packages\django\template\backends\django.py", line 61, in render
return self.template.render(context)
File "C:\python-win\myenv\lib\site-packages\django\template\base.py", line 169, in render
with context.bind_template(self):
File "c:\python38\lib\contextlib.py", line 113, in __enter__
return next(self.gen)
File "C:\python-win\myenv\lib\site-packages\django\template\context.py", line 246, in bind_template
updates.update(processor(self.request))
File "C:\python-win\app\loads\context_processors.py", line 10, in variable
except assistant.DoesNotExist:
UnboundLocalError: local variable 'assistant' referenced before assignment
[10/May/2020 19:38:48] "GET / HTTP/1.1" 500 101883
Not Found: /favicon.ico
----------------------------------------

Solution for the above output error message is simple. Just initialize the variable with the name of ‘assistant’. The above error happens because it is failing to get a value. There is a line where the variable is expecting the value from it. It is from the query execution by the definition of the ‘get’ method of the objects in this line :

assistant = Assistant.objects.get(user=request.user)

Find another way or method to define the solution to be able to initialize or to fill the variable.

Leave a Reply