ユーザーがフォームに送信したテキストを含む名前をデータベースで検索するdjangoビューがあります。
検索に使用するときは、各レコードのフィールドとフィールド.filter
に対してユーザーのクエリを確認します。それはすべて機能しますが、私の問題は、ユーザーが検索ボックスに空白を使用してフルネームを入力した場合(たとえば、「john」または「smith」の代わりに「John Smith」)、関数が結果を返さないことです。first_name
last_name
これらすべてにまったく新しいので、関数やフォームを変更する方法がわかりません。怠惰になってスペースキー(それは可能だと思います)などを入力できないようにすることもできますが、問題の実際の解決策を学びたいですか?
フォームとビューは次のとおりです。非常にシンプルです。
<form action="/Speakers/Search" method="get">
<input type="text" name="q">
<input type="submit" value=" Search ">
</form>
完全な副次的な質問:私は行折り返しのあるテキストエディタを使用しているので、Pythonで行区切りを追加することが「安全」な場所がまだわからないことを忘れましたか?重要なのはインデントだけですか..?したがって、以下のコードをスクロールする必要があることをお詫びします。
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})