Skip to content

Commit 27fae6f

Browse files
author
yangxg
committed
Step25: simple search
1 parent 304d6bd commit 27fae6f

File tree

4 files changed

+21
-2
lines changed

4 files changed

+21
-2
lines changed

blog/urls.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,4 +9,5 @@
99
url(r'^archives/(?P<year>[0-9]{4})/(?P<month>[0-9]{1,2})/$', views.ArchivesView.as_view(), name='archives'),
1010
url(r'^category/(?P<pk>[0-9]+)/$', views.CategoryView.as_view(), name='category'),
1111
url(r'^tag/(?P<pk>[0-9]+)/$', views.TagView.as_view(), name='tag'),
12+
url(r'^search/$', views.search, name='search'),
1213
]

blog/views.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
from markdown.extensions.toc import TocExtension
44

5+
from django.db.models import Q
56
from django.shortcuts import render, get_object_or_404
67
from django.views.generic import ListView, DetailView
78
from django.utils.text import slugify
@@ -297,3 +298,16 @@ class TagView(ListView):
297298
def get_queryset(self):
298299
tag = get_object_or_404(Tag, pk=self.kwargs.get('pk'))
299300
return super(TagView, self).get_queryset().filter(tags=tag)
301+
302+
303+
def search(request):
304+
q = request.GET.get('q')
305+
error_msg = ''
306+
307+
if not q:
308+
error_msg = "请输入关键词"
309+
return render(request, 'blog/index.html', {'error_msg': error_msg})
310+
311+
post_list = Post.objects.filter(Q(title__icontains=q) | Q(body__icontains=q))
312+
return render(request, 'blog/index.html', {'error_msg': error_msg,
313+
'post_list': post_list})

templates/base.html

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -52,8 +52,8 @@ <h1><a href="{% url 'blog:index' %}"><b>Black</b> &amp; White</a></h1>
5252
<div id="header-search-box">
5353
<a id="search-menu" href="#"><span id="search-icon" class="ion-ios-search-strong"></span></a>
5454
<div id="search-form" class="search-form">
55-
<form role="search" method="get" id="searchform" action="#">
56-
<input type="search" placeholder="搜索" required>
55+
<form role="search" method="get" id="searchform" action="{% url 'blog:search' %}">
56+
<input type="search" name="q" placeholder="搜索" required>
5757
<button type="submit"><span class="ion-ios-search-strong"></span></button>
5858
</form>
5959
</div>

templates/blog/index.html

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11
{% extends 'base.html' %}
22

33
{% block main %}
4+
{% if error_msg %}
5+
<p>{{ error_msg }}</p>
6+
{% endif %}
7+
48
{% for post in post_list %}
59
<article class="post post-{{ post.pk }}">
610
<header class="entry-header">

0 commit comments

Comments
 (0)