0
votes

i have a function in views.py that list all records and allow user to search for specific record where if filter the class "suspect" the problem that i got is once i tried to search the system crash and display the below error :

local variable 'ListQuery' referenced before assignment Request Method: GET Request URL: http://127.0.0.1:8000/blog/list/ Django Version: 2.1.3 Exception Type: UnboundLocalError Exception Value:
local variable 'ListQuery' referenced before assignment Exception Location: C:\Users\LT GM\Desktop\ABenvironment\myABenv\blog\views.py in listANDsearch, line 186 Python Executable: C:\Users\LT GM\AppData\Local\Programs\Python\Python37\python.exe Python Version: 3.7.1

Traceback

Environment:

Request Method: GET Request URL: http://127.0.0.1:8000/blog/list/

Django Version: 2.1.3 Python Version: 3.7.1 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', 'widget_tweaks', 'import_export'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', '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:\Users\LT GM\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request)

File "C:\Users\LT GM\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request)

File "C:\Users\LT GM\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Users\LT GM\Desktop\ABenvironment\myABenv\blog\views.py" in listANDsearch 186. elif ListQuery == []:

Exception Type: UnboundLocalError at /blog/list/ Exception Value: local variable 'ListQuery' referenced before assignment

views.py

def listANDsearch(request):
    #deny anonymouse user to enter the  list page
    if not request.user.is_authenticated:
            return redirect("login")
    else:
        queryset = suspect.objects.all()
        # return render(request,"blog/list.html", {"object_list":queryset})

        #search 
        query=request.GET.get("q")
        print("search for :",query)

        if query == "":
            messages.error(request,"Search field is empty!")
            print("Search field is empty!!!!!!!!!!!!!!!!")

        elif query:

            queryset_list=queryset_list.filter(
              Q(suspect_name__icontains=query)|
              Q(suspect_father_name__icontains=query)|
              Q(suspect_mother_name__icontains=query)|
              Q(content__icontains=query)|
              Q(create_date__icontains=query)
                  # Q(user__first_name__contains=query)
            ).distinct()
            ListQuery = list(queryset_list)
            #paginator in order to make several pages 
            paginator = Paginator(queryset_list, 10) # Show 5 items per page
            page_request_var = "page"#this line to change dynamicly the string befor the number of page like **page 1** or **abc 1**
            page = request.GET.get(page_request_var)
            queryset = paginator.get_page(page)

            context={
                "object_list":queryset,
                "title":"List Items",
                "page_request_var":page_request_var,
            }
            return render(request,"blog/list.html", context)
        elif ListQuery == []:
            messages.error(request,"Record not found/does not exist!")
            print("Record does not exist!!!!!!!!!!!!!!!!")
1

1 Answers

0
votes

You have an if statement with 3 separate conditions. You have defined ListView in the second one and trying to access it in the third conditional statement. Therefore you are getting this error. You need to update your code such as:

# views.py
def listANDsearch(request):
    try:
        #deny anonymouse user to enter the  list page
        if not request.user.is_authenticated:
            return redirect("login")
        else:
            queryset = suspect.objects.all()
            # return render(request,"blog/list.html", {"object_list":queryset})

            #search 
            query=request.GET.get("q")
            print("search for :",query)

            if query == "":
                messages.error(request,"Search field is empty!")
                print("Search field is empty!!!!!!!!!!!!!!!!")
                return redirect("login")

            elif query:

                queryset_list=queryset_list.filter(
                  Q(suspect_name__icontains=query)|
                  Q(suspect_father_name__icontains=query)|
                  Q(suspect_mother_name__icontains=query)|
                  Q(content__icontains=query)|
                  Q(create_date__icontains=query)
                      # Q(user__first_name__contains=query)
                ).distinct()
                ListQuery = list(queryset_list)

                # move your conditional statement here
                if ListQuery == []:
                    messages.error(request,"Record not found/does not exist!")
                    print("Record does not exist!!!!!!!!!!!!!!!!")
                    return redirect("login")
                else:
                    #paginator in order to make several pages 
                    paginator = Paginator(queryset_list, 10) # Show 5 items per page
                    page_request_var = "page"#this line to change dynamicly the string befor the number of page like **page 1** or **abc 1**
                    page = request.GET.get(page_request_var)
                    queryset = paginator.get_page(page)

                    context={
                        "object_list":queryset,
                        "title":"List Items",
                        "page_request_var":page_request_var,
                    }
                    return render(request,"blog/list.html", context)
    except Exception as e:
        print("Exception occurred.")
        return redirect("login")