卡洛斯切拉,保尔呕心沥血写小说,男篮热身赛直播
附上个人网站:
注意:这里我们不安装django-haystack,因为要添加中文分词的功能很麻烦,所以我直接集成了一个中文的django-haystack包
下载地址:https://github.com/pythonerkk/django-haystack-chinese/
pip安装whoosh和jieba:
pip install whoosh jieba
新建一个名为extra_apps
的目录,把django-haystack包复制进去:
把extra_apps目录设置为项目搜索根目录,修改settings.py
文件
import sys base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, os.path.join(base_dir, 'extra_apps'))
添加到install_app中,修改settings.py
文件
installed_apps = [ ... 'haystack', ]
继续修改settings.py
,添加haystack配置项
haystack_connections = { 'default': { 'engine': 'haystack.backends.whoosh_cn_backend.whooshengine', 'path': os.path.join(base_dir, 'whoosh_index'), } } # 每页显示搜索结果数目为10 haystack_search_results_per_page = 10 # 自动生成索引 haystack_signal_processor = 'haystack.signals.realtimesignalprocessor'
然后在项目的urls.py
中加入:
urlpatterns = [ ... path('search/', include('haystack.urls')) ]
在自己的app中添加search_indexes.py文件
search_indexes.py
文件内容
from haystack import indexes from .models import post class ideaindex(indexes.searchindex, indexes.indexable): text = indexes.charfield(document=true, use_template=true) def get_model(self): # 这里修改成你自己的数据库模型 return post def index_queryset(self, using=none): return self.get_model().objects.all()
在templates文件下新增一个目录search/indexes/(你的app名)/(你的app名)_text.txt:
xxx_text.txt
这里填写要搜索的字段名称
{{ object.title }} {{ object.content }}
添加后修改search.html
<!doctype html> <html> <head> <title></title> </head> <body> {% if query %} <h3>搜索结果如下:</h3> {% for result in page.object_list %} <a href="/jiablog/article/{{ result.object.id }}/">{{ result.object.title }}</a><br/> {% empty %} <p>啥也没找到</p> {% endfor %} {% if page.has_previous or page.has_next %} <div> {% if page.has_previous %}<a href="?q={{ query }}&page={{ page.previous_page_number }}">{% endif %}« 上一页{% if page.has_previous %}</a>{% endif %} | {% if page.has_next %}<a href="?q={{ query }}&page={{ page.next_page_number }}">{% endif %}下一页 »{% if page.has_next %}</a>{% endif %} </div> {% endif %} {% endif %} </body> </html>
这个非常简单,直接在模板中引入如下字段即可
search.html
{% load highlight %} <style> span.highlighted { color: red; } </style> ... {% highlight query with xxx.object.title %}
如上所示,query就是代表搜索关键字,只需要一句代码就可以完成高亮
按照上述步骤,应该就能成功了,接下来我们来重建索引
python manage.py rebuild_index
运行后选择y,然后就会提示建立索引成功
这里必须严格按照这个结构创建,需要注意.txt文件名要全部小写!!
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
新手学习Python2和Python3中print不同的用法
Python基于os.environ从windows获取环境变量
网友评论