0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Django2.0でブログの作成(その9:記事の検索)

Last updated at Posted at 2018-10-09

その9

記事を検索したい時ってありますよね?
トップページに検索ボックスと検索ボタンをつけて、記事タイトル検索をしましょう!

forms.py

検索ボックスもformですよね?
次のclassを追加しましょう。

blog/forms.py
class SearchForm(forms.Form):
    q = forms.CharField(label="検索")

qは一般的にqueryです。なんでもいいですが、qがわかりやすそうです。

views.py

今回はdef post_list内の処理でよさそうです。

views.py
def post_list(request):
    posts = Post.objects.all()
    form = forms.SearchForm()
    print(request.GET)

    if request.GET.get('q'):
        posts = posts.filter(title__contains = request.GET.get('q')) #titleにqを含む、部分一致検索が可能

    return render(request, 'blog/post_list.html', {
        'posts': posts,
        'form': form
    })

return renderの中にformも追加してくださいね。

urls.py

ページ内処理なので変更ありません。

post_list.html

post_list.html
<form method="get" action="">
  {{ form }}
  <input type="submit" value="検索">
</form>

確認

スクリーンショット 2018-10-09 17.31.17.png
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?