django2 search form UnboundLocalError at /

Question:

I try to add a search box with this code’s i got the error:

Blank result

def home(request):
    if 'search' in request.GET:
        term = request.GET['search']
        name = Products.objects.filter(titulo__icontains=term)
    return render(request,'base.html', {'name':name})

in the model:

from django.db import models
    class Products(models.Model):
        name = models.CharField(max_length=255, blank=True, null=True)
      def __str__(self):
            return self.name

on the views

from django.shortcuts import render
from .models import Products
def home(request):
    if 'search' in request.GET:
        term = request.GET['search']
        item = Products.objects.filter(name__icontains=term)
    return render(request,'base.html', {'item':item})

if i use this i got the error
local variable ‘name’ referenced before assignment
And if i add the variable name

from django.shortcuts import render
    from .models import Products
    def home(request):
        item=none
        if 'search' in request.GET:
            term = request.GET['search']
            item = Products.objects.filter(name__icontains=term)
        return render(request,'base.html', {'item':item}) 

edited the second view, with this i don’t have results using

{{Products.name}}

on the html file
i also try with:

def home(request):
    query = request.GET.get('search',None)
    items = Products.objects.all()
    if query is not None:
        items = items.filter(
            Q(items__contains=query)
            )
    context = {'items':items}
    return render(request, 'base.html', context)
Asked By: Laut

||

Answers:

In all your views, you make more or less the same mistake:

def home(request):
    if 'search' in request.GET:
        term = request.GET['search']
        name = Products.objects.filter(titulo__icontains=term)
    return render(request,'base.html', {'name': name})

You here define a variable, for example name in the if body. But now imagine that the condition in the if statement is not true, then it will skip the body. After the if body however you use the name variable. Now in case the statement is not true, you use a variable that was never defined.

You can fix this, for example by defining a default value first:

def home(request):
    name = Products.objects.all()
    if 'search' in request.GET:
        term = request.GET['search']
        name = Products.objects.filter(titulo__icontains=term)
    return render(request,'base.html', {'name': name})

So now in case the condition is not true, then the variable is still set, since we defined it before the if statement, here for example we return than all products.

In your second view, the same happens, but now the culprit is the item variable.

Answered By: Willem Van Onsem
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.