I have a django view that searches my database for a name that includes the text a user submitted on a form.
When i use .filter to search i check the users query against the first_name and last_name fields of each record. It all works but my problem is, if a user entered the full name in the search box with whitespace (eg. “John Smith” instead of “john” or “smith” my function would return no results!
Quite new to all this and I’m not sure how i would go about changing the function or even the form. I could just be lazy and prevent them from entering the space key (I presume that’s possible) or something but i’d like to learn the actual solution to my problem?
Here’s the form and the view, they’re pretty simple:
<form action="/Speakers/Search" method="get">
<input type="text" name="q">
<input type="submit" value=" Search ">
</form>
Complete side question: Just realised, because i have been using a text editor with line-wrap, i forgot i still don’t know where it’s “safe” to add things line line-breaks in python? is it only the indentation that matters..? So apologies for having to scroll the code below:
def SearchSpeakers(request):
if 'q' in request.GET and request.GET['q']: #2nd condition return false if emtpy string
search = request.GET['q']
message = "You searched for: %s." % search
results = Speaker.objects.filter(Q(first_name__icontains=search) | Q(last_name__icontains=search))
if not results: #returned empty
message += " We could not find the name you entered in our Speakers List but you check back again before the event! Press clear to see the complete list again."
return render_to_response('Speakers.html', {'speakers':results, 'query': message})
else:
message = "You did not enter a name."
return render_to_response('Speakers.html',{'query':message})
It looks like your issue is that you are searching the first_name or last_name field with the whole_name. You could add some logic that checks the input (splits on whitespace or comma’s) and searches each member of the whole name in a loop. I’m not familiar with Django but