UnboundLocalError - local variable 'emprendedores' referenced before assignment

I can't figure out why am I getting this error message: "UnboundLocalError - local variable 'emprendedores' referenced before assignment"

enter image description here

Hey fellows, i'm building an app in Django and almost is pretty well. However, I cannot find solution to a problem in my search view. The main idea is allowing the user to indicate the word and to select the desired fields to search into from an form, and returning the registered users that satisfy the criteria.

The html file looks like this:

enter image description here

This is the model:

enter image description here

and this is the view I'm working on:

enter image description here

But I can't figure out why am I getting this error message: "UnboundLocalError - local variable 'emprendedores' referenced before assignment"

enter image description here

I'll be glad if someone can help my out.

This is the error:

UnboundLocalError at /consulta/ local variable 'emprendedores' referenced before assignment Request Method: POST Request URL: http://127.0.0.1:8000/consulta/ Django Version: 3.2.8 Exception Type: UnboundLocalError Exception Value:
local variable 'emprendedores' referenced before assignment Exception Location: C:\Users\Jobert Gutierrez\Documents\PROYECTOS\DESPRO\BARDEP\views.py, line 112, in Consulta Python Executable: C:\ProgramData\Anaconda3\python.exe Python Version: 3.9.7

This is the View:

def Consulta(request):
    if request.method == "POST":
        #fields = Emprendedores._meta.get_fields()
        fields = request.POST.getlist('campos')
        busqueda = request.POST['busqueda']
        query = Q()
        if (busqueda.isnumeric()):
            emprendedores = Emprendedores.objects.filter(numerodocumento__contains=busqueda)
            messages.success(request,("No existen coincidencias para su búsqueda"))
        else:
            for columna in fields:
                if columna in Emprendedores._meta.get_fields():
                    condicion = {f'{columna}__icontains': busqueda }
                    query |= Q(**condicion)
                    query.connector = 'OR'
                    emprendedores = Emprendedores.objects.filter(query)  
                elif columna in SectorEconomico._meta.get_fields():
                    query1 = SectorEconomico.objects.filter(nombresector__icontains=busqueda)   
                    emprendedores = Emprendedores.objects.filter(sectoreco__pk=F('query1__pk'))
                return emprendedores
            return emprendedores
        return render(request,'buscados.html',{'emprendedores':emprendedores})
    else:
        return render(request,'consulta.html')

How can I send it to the view?

Back to Top