"Cannot use None as a query value" in django search filter showing this error

Viewed 10917

I'm trying to implement search bar in django, if search item present in Database i'm displaying in web page. But its showing query returns None value. I'm new to django.Please help me in this

views.py

def search(request):
    if request.method == 'GET':
        form = LocForm(request.POST)
        if form.is_valid():
            search_query = request.GET.get('search_box', None)
            print(search_query)
            FirstLoc_list_obj = FirstLoc_List.objects.filter(address__icontains=search_query)
            SecondLoc_list_obj= SecondLoc_list.objects.filter(address__icontains=search_query)
            if (len(FirstLoc_list_obj) or len(SecondLoc_list_obj)) > 0:
                print("Locaton Found")
                return render(request, 'location_test.html', {'FirstLoc_list_obj': FirstLoc_list_obj, 'SecondLoc_list_obj': SecondLoc_list_obj})
            else:
                print("Location Not Found")
                return render(request, 'location_test.html', {})
            return render(request, 'location_test.html', {})
        return render(request, 'location_test.html', {})

urls.py

urlpatterns = [
    path('search/', views.search, name="search"),
]

location_test.html

<form type="get" action="#" style="margin: 0">
    {% csrf_token %}
<label>Locations:-</label>
    <input  id="search_box" type="text" name="search_box"  placeholder="Search..." >
    <button id="search_submit" type="submit" >Submit</button>
</form>
4 Answers

As I said in comment you cannot use icontains with None value. Try this:

def search(request):
    if request.method == 'GET':
        form = LocForm(request.POST)
        if form.is_valid():
            search_query = request.GET.get('search_box', None)
            if search_query:
                FirstLoc_list_obj = FirstLoc_List.objects.filter(address__icontains=search_query)
                SecondLoc_list_obj= SecondLoc_list.objects.filter(address__icontains=search_query)

you can use an empty string if None, for example :

search_query = request.GET.get('search_box')

if not search_query :
    search_query = ""

This is the only place that discuss this error. So this is not the perfect answer of the question, but i hope it will be usefull for others.

I don't have a form but a URL to check, but when a user get on the page on a way i didn't intend, it shouldn't raise an error. So i put everything inside a if statement.

if request.GET.get("q") != None:
        query = request.GET.get("q")
        context["array"] = Database.objects.filter(DB__item__contains=query)
def search(request):
    if request.method == 'GET':
        form = LocForm(request.POST)
        if form.is_valid():
            enter code heresearch_query = request.GET.get('search_box', '')
            FirstLoc_list_obj = FirstLoc_List.objects.filter(address__icontains=search_query)
Related