django全文检索和富文本编辑器

富文本编辑器

安装模块 pip install django-tinymce==2.6.0,安装完成后,可以使用在Admin管理中,也可以自定义表单使用。

在admin页面使用

settings.py

INSTALLED_APPS = (
    ...
    'tinymce',
)

TINYMCE_DEFAULT_CONFIG = {
    'theme': 'advanced',
    'width': 600,
    'height': 400,
}

urls.py

urlpatterns = [
    ...
    url(r'^tinymce/', include('tinymce.urls')),
]

models.py

from django.db import models
from tinymce.models import HTMLField

class Book(models.Model):
    # 最终保存到数据库的是带有html标签的字符串
    content=HTMLField()

admin.py

from django.contrib import admin
from booktest.models import *
class BookAdmin(admin.ModelAdmin):
    list_display = ['id']

admin.site.register(Book,BookAdmin)

自定义使用

  1. 在site-packages/tinymce/static/tiny_mce目录拷贝tiny_mce_src.js文件、langs文件夹以及themes文件夹拷贝到项目目录下的static/js/目录下
  2. 在相应模版引入tiny_mce_src.js文件
<html>
<head>
    <title>自定义使用tinymce</title>
    <script type="text/javascript" src='/static/js/tiny_mce.js'></script>
    <script type="text/javascript">
        tinyMCE.init({
            'mode':'textareas',
            'theme':'advanced',
            'width':400,
            'height':100
        });
    </script>
</head>
<body>
<form method="post" action="#">
    <textarea name='content'>孙悟空三打白骨精</textarea>
</form>
</body>
</html>

django 全文搜索

全文检索不同于特定字段的模糊查询,使用全文检索的效率更高,并且能够对于中文进行分词处理。

  • haystack:全文检索的框架,支持whoosh、solr、Xapian、Elasticsearc四种全文检索引擎,点击查看官方网站。
  • whoosh:纯Python编写的全文搜索引擎,虽然性能比不上sphinx、xapian、Elasticsearc等,但是无二进制包,程序不会莫名其妙的崩溃,对于小型的站点,whoosh已经足够使用,点击查看whoosh文档。
  • jieba:一款免费的中文分词包,用于whoosh的分词效果不好的补充

  • 安装依赖包:
pip3 install django-haystack
pip3 install whoosh
pip3 install jieba
  • 在site-packages/haystack/backends/目录创建ChineseAnalyzer.py文件
import jieba
from whoosh.analysis import Tokenizer, Token

class ChineseTokenizer(Tokenizer):
    def __call__(self, value, positions=False, chars=False,
                 keeporiginal=False, removestops=True,
                 start_pos=0, start_char=0, mode='', **kwargs):
        t = Token(positions, chars, removestops=removestops, mode=mode,
                  **kwargs)
        seglist = jieba.cut(value, cut_all=True)
        for w in seglist:
            t.original = t.text = w
            t.boost = 1.0
            if positions:
                t.pos = start_pos + value.find(w)
            if chars:
                t.startchar = start_char + value.find(w)
                t.endchar = start_char + value.find(w) + len(w)
            yield t

def ChineseAnalyzer():
    return ChineseTokenizer()
  • 复制whoosh_backend.py文件,改为如下名称whoosh_cn_backend.py
  • 打开复制出来的新文件,引入中文分析类,内部采用jieba分词。from .ChineseAnalyzer import ChineseAnalyzer
  • 更改词语分析类
查找
analyzer=StemmingAnalyzer()
改为
analyzer=ChineseAnalyzer()
  • settings.py
INSTALLED_APPS = (
    ...
    'haystack',
)

...
HAYSTACK_CONNECTIONS = {
    'default': {
        #使用whoosh引擎
        'ENGINE': 'haystack.backends.whoosh_cn_backend.WhooshEngine',
        #索引文件路径
        'PATH': os.path.join(BASE_DIR, 'whoosh_index'),
    }
}

#当添加、修改、删除数据时,自动生成索引
HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'

urls.py添加一条记录:url(r'^search/', include('haystack.urls'))

  • 在对应的app目录下创建search_indexes.py文件,这里的app是app01
from haystack import indexes
from booktest.models import GoodsInfo
#指定对于某个类的某些数据建立索引
class BookIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.CharField(document=True, use_template=True)

    def get_model(self):
        return Book

    def index_queryset(self, using=None):
        # 对所有对象做分词
        return self.get_model().objects.all()
  • 在templates目录下创建"search/indexes/app01/"目录
  • 在上面的目录中创建"book_text.txt"文件,名字是模型名小写_text.txt,
# 指定索引的属性
{{object.content}}
  • 生成索引文件:python manage.py rebuild_index
  • 使用
<html>
<head>
    <title>全文检索</title>
</head>
<body>
<form method='get' action="/search/" target="_blank">
    <input type="text" name="q">
    <br>
    <input type="submit" value="查询">
</form>
</body>
</html>

请求方式必须是get,name必须是q。

  • templates/search/目录下创建search.html,搜索结果进行分页,视图向模板中传递的上下文如下:
    query:搜索关键字
    page:当前页的page对象
    paginator:分页paginator对象

视图接收的参数如下:

    参数q表示搜索内容,传递到模板中的数据为query
    参数page表示当前页码
<html>
<head>
    <title>全文检索--结果页</title>
</head>
<body>
<h1>搜索&nbsp;<b>{{query}}</b>&nbsp;结果如下:</h1>
<ul>
{%for item in page%}
    <li>{{item.object.id}}--{{item.object.|safe}}</li>
{%empty%}
    <li>啥也没找到</li>
{%endfor%}
</ul>
<hr>
{%for pindex in page.paginator.page_range%}
    {%if pindex == page.number%}
        {{pindex}}
    {%else%}
        <a href="?q={{query}}&amp;page={{pindex}}">{{pindex}}</a>
    {%endif%}
{%endfor%}
</body>
</html>

猜你喜欢

转载自www.cnblogs.com/longyunfeigu/p/9619911.html
今日推荐