简体   繁体   中英

Django context : local variable referenced before assignment

Good afternoon everybody,

I'm getting a little problem with my context variables in my Django project . I have a function which let me to make some processes. Especially some reasearches over my database and display the result.

But I have a problem with one variable : folderId

I'm getting this error and I don't find a way to overcome it :

Environment:


Request Method: GET
Request URL: http://localhost:8000/Identity/recherche

Django Version: 1.10.3
Python Version: 2.7.12
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'BirthCertificate',
 'Identity',
 'bootstrapform',
 'Accueil',
 'captcha',
 'django_countries',
 'log',
 'Mairie',
 'Table',
 'Recensement']
Installed Middleware:
['django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.locale.LocaleMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.middleware.gzip.GZipMiddleware',
 '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 "/usr/local/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner
  39.             response = get_response(request)

File "/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py" in _legacy_get_response
  249.             response = self._get_response(request)

File "/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response
  187.                 response = self.process_exception_by_middleware(e, request)

File "/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response
  185.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/usr/local/lib/python2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
  23.                 return view_func(request, *args, **kwargs)

File "/Users/valentinjungbluth/Desktop/Django/Etat_civil/Identity/views.py" in Identity_Researching
  121.         "folderId" : folderId,

Exception Type: UnboundLocalError at /Identity/recherche
Exception Value: local variable 'folderId' referenced before assignment

My function looks like :

@login_required
def Identity_Researching(request) :

    #######################
    # Display some arrays #
    #######################

    identitys = Identity.objects.order_by("-id")
    identity = identitys[:3] #The 3 last created forms
    identity_France = identitys.filter(country=64)[:3] #The 3 last created form with BirthCity = France

    ############################
    # People searching process #
    ############################

    query_lastname = request.GET.get('q1')
    query_firstname = request.GET.get('q1bis')
    query_birthday = request.GET.get('q1ter')

    if query_lastname or query_firstname or query_birthday :

        query_lastname_list = Identity.objects.filter(lastname__contains=query_lastname, firstname__contains=query_firstname, birthday__contains=query_birthday) 

        title = str(query_lastname + "_" + query_firstname + "_" + query_birthday)

        ##########################################
        # Look if people directory already exist #
        ##########################################

        url = 'http://demodoc/services/rest/folder/listChildren?folderId=8552450'
        payload = {'folderId': 8552450}

        headers = {'Accept': 'application/json'}
        r = requests.get(url,  params=payload, headers=headers, auth=('etatcivil', '100%EC67'))

        rbody = r.content
        data = json.loads(rbody)

        longueur = len(data)

        i=0
        list = []

        while i < longueur :

            if data[i]["name"] == title :

                list = [data[i]]

            i = i+1

        ############################################
        # We have correspondance, use ID directory #
        ############################################

        if len(list) == 1 :

            folderId = list[0]["id"]

        else : 

            return HttpResponseRedirect('searched')

    else :
        query_lastname_list = Identity.objects.none() # == []


    if "Retour" in request.POST :
        return HttpResponseRedirect('accueil')

    context = {
        "identity" : identity,
        "identity_France" : identity_France,
        "query_lastname" : query_lastname,
        "query_firstname" : query_firstname,
        "query_birthday" : query_birthday,
        "query_lastname_list" : query_lastname_list,
        "folderId" : folderId,
        }

    return render(request, 'resume.html', context)

Did I miss something or the order is not correct ? When I have this kind of error, I don't understand very well what I have to do in order to overcome it ..

Thank you for any help :)

You are using a variable instantiated inside an if statement. Simply create it outside first:

def Identity_Researching(request):
    folderId = None
    ...

Expanding on @Gianluca's answer, take a look at this simple example:

list = [1,2]
if len(list) == 1:
    folderId = list[0]

print(folderId)

In this situation which is similar to the way your program works, folderId never gets defined and so a NameError will be thrown when trying to print the undefined variable. However, using this:

folderId = None
list = [1,2]
if len(list) == 1:
    folderId = list[0]

print(folderId)

Will instead print None as folderId has been defined, even if it's value is None .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM