Skip to content

Latest commit

 

History

History
95 lines (73 loc) · 3.25 KB

十五、增加搜索功能.md

File metadata and controls

95 lines (73 loc) · 3.25 KB
title date tags
增加搜索功能
2018-04-08 07:08:08 -0700
DJANGO

十五、增加搜索功能

搜索框可以直接参考bootstrap框架,在导航分类的右侧加入

# base.html


<header class="fixed-top">
      <div class="container">
          <div class="row">
              <div class="col-8">
                <nav class="nav">
                    <a class="log" href="/">Myblog</a>
                    <a class="index" href="/">首页</a>
                    {% for cate in nav_cates %}
                    <a class="link" href="{% url 'category' cate.id %}">{{ cate.name }}</a>
                    {% endfor %}
                </nav>
              </div>
              <div class="col-4">
                  <nav class="navbar">
                      <form class="form-inline">
                        <input class="form-control mr-sm-2" name="query" type="search" aria-label="Search">
                        <button class="btn btn-outline-success my-2 my-sm-0" type="submit">搜索</button>
                      </form>
                  </nav>
              </div>
          </div>
      </div>
  </header>

运行服务可以看到搜索框出现在了分类导航的右侧,但它仅仅只是一个样式,不具备搜索功能

接下来我们在blog/views.py中来实现搜索功能,先过滤数据,再把数据传递到模板,request.GET.get(query):通过get请求获取的数据都存放在request.GET中,所以它是一个字典对象,用get来获取query键。接下来,通过super函数我们调用IndexView父类的get_queryset方法来获取所有文章数据。最后,如果query存在就过滤出所有以query开头的数据,i表示不区分大小写,如果query不存在就返回。后面我们再创建get_context_data()方法把数据传递到模板,在搜索框表单中加入name=query

class IndexView(BasePostView):
    """增加搜索功能
    1、数据过滤
    2、数据传递到模板里
    3、request.GET.get(query):通过get请求获取的数据都存放在request.GET中,
    所以它是一个字典对象,用get来获取query键
    4、通过super函数我们调用IndexView的get_queryset方法来获取所有文章数据
    5、如果query存在就过滤出所有以query开头的数据,i表示不区分大小写,
    如果query不存在就返回
    """
    def get_queryset(self):
        query = self.request.GET.get("query")
        qs = super(IndexView, self).get_queryset()
        if query:
            qs = qs.filter(title__icontains=query)
        return qs

    def get_context_data(self, **kwargs):
        query = self.request.GET.get('query')
        return super(IndexView, self).get_context_data(query=query)
# base.html

 <input class="form-control mr-sm-2" name="query" type="search" aria-label="Search">

最后,再增加一个功能,“搜索功能提示”

{% block content %}
{% if query %}
    您搜索的: {{ query }} 结果如下:
{% endif %}
<hr/>

运行服务查看下搜索功能

GitHub 欢迎访问Treehl的博客