This view works when the query is in the database.
def search(request):
if 'q' in request.GET and request.GET['q']:
q = request.GET['q']
q_school = Lawyer.objects.filter(last__icontains=q).values_list('school', flat=True)
q_year = Lawyer.objects.filter(last__icontains=q).values_list('year_graduated', flat=True)
lawyers = Lawyer.objects.filter(school__icontains=q_school[0]).filter(year_graduated__icontains=q_year[0]).exclude(last__icontains=q)
return render_to_response('search_results.html', {'lawyers': lawyers, 'query': q})
else:
return HttpResponse('Please submit a search term.')
So, if q=delelle then it finds other lawyers in the database who graduated from the same school the same year.
if q=collins and collins is in the database but there are no other lawyers who graduated from the same school the same year then it gives appropriate error message "No lawyers matched your search criteria."
But if q=moritz and there is no lawyer named moritz
in the database then it gives a 500 internal server error.
I don't understand the request.GET['q']
notation or how I can fix this so that I can add the proper text for the case when the query is not in the database. Can you please point me in the right direction? Thanks.
Edit re Antony Hatchkins answer
The below code works without giving the error. I will try to incorporate the rest soon:
def search(request):
if 'q' in request.GET and request.GET['q']:
q = request.GET['q']
lawyer = Lawyer.objects.filter(last__icontains=q)
if len(lawyer)==0:
return render_to_response('not_in_database.html', {'query': q})
else:
q_school = Lawyer.objects.filter(last__icontains=q).values_list('school', flat=True)
q_year = Lawyer.objects.filter(last__icontains=q).values_list('year_graduated', flat=True)
lawyers = Lawyer.objects.filter(school__icontains=q_school[0]).filter(year_graduated__icontains=q_year[0]).exclude(last__icontains=q)
return render_to_response('search_results.html', {'lawyers': lawyers, 'query': q})
else:
return HttpResponse('Please submit a search term.')