Skip to content

Commit 83064c1

Browse files
author
zmrenwu
committed
Step27: simple search
1 parent 9b3fbd1 commit 83064c1

File tree

4 files changed

+19
-3
lines changed

4 files changed

+19
-3
lines changed

Diff for: README.md

+1
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,7 @@ tutorial 分支为项目的主分支,每一篇教程的代码都和历史提
147147
24. [稳定易用的 Django 分页库,完善分页功能](https://www.zmrenwu.com/courses/hellodjango-blog-tutorial/materials/82/)
148148
25. [统计各个分类和标签下的文章数](https://www.zmrenwu.com/courses/hellodjango-blog-tutorial/materials/83/)
149149
26. [开启 Django 博客的 RSS 功能](https://www.zmrenwu.com/courses/hellodjango-blog-tutorial/materials/84/)
150+
27. [Django 博客实现简单的全文搜索](https://www.zmrenwu.com/courses/hellodjango-blog-tutorial/materials/85/)
150151

151152
## 公众号
152153
<p align="center">

Diff for: blog/urls.py

+1
Original file line numberDiff line numberDiff line change
@@ -9,4 +9,5 @@
99
path('archives/<int:year>/<int:month>/', views.ArchiveView.as_view(), name='archive'),
1010
path('categories/<int:pk>/', views.CategoryView.as_view(), name='category'),
1111
path('tags/<int:pk>/', views.TagView.as_view(), name='tag'),
12+
path('search/', views.search, name='search'),
1213
]

Diff for: blog/views.py

+15-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1-
from django.shortcuts import get_object_or_404
1+
from django.contrib import messages
2+
from django.db.models import Q
3+
from django.shortcuts import get_object_or_404, redirect, render
24
from django.views.generic import DetailView, ListView
35

46
from pure_pagination.mixins import PaginationMixin
@@ -56,3 +58,15 @@ def get(self, request, *args, **kwargs):
5658

5759
# 视图必须返回一个 HttpResponse 对象
5860
return response
61+
62+
63+
def search(request):
64+
q = request.GET.get("q")
65+
66+
if not q:
67+
error_msg = "请输入搜索关键词"
68+
messages.add_message(request, messages.ERROR, error_msg, extra_tags="danger")
69+
return redirect("blog:index")
70+
71+
post_list = Post.objects.filter(Q(title__icontains=q) | Q(body__icontains=q))
72+
return render(request, "blog/index.html", {"post_list": post_list})

Diff for: templates/base.html

+2-2
Original file line numberDiff line numberDiff line change
@@ -84,8 +84,8 @@ <h1><a href="{% url 'blog:index' %}"><b>Black</b> &amp; White</a></h1>
8484
<div id="header-search-box">
8585
<a id="search-menu" href="#"><span id="search-icon" class="ion-ios-search-strong"></span></a>
8686
<div id="search-form" class="search-form">
87-
<form role="search" method="get" id="searchform" action="#">
88-
<input type="search" placeholder="搜索" required>
87+
<form role="search" method="get" id="searchform" action="{% url 'blog:search' %}">
88+
<input type="search" name="q" placeholder="搜索" required>
8989
<button type="submit"><span class="ion-ios-search-strong"></span></button>
9090
</form>
9191
</div>

0 commit comments

Comments
 (0)