You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.
# 导入Python内置logging模块, 用于记录搜索相关日志( 如搜索关键词)
import logging
# 导入Django表单基础模块, 用于创建自定义表单字段
from django import forms
# 从Haystack库导入基础搜索表单类SearchForm, Haystack是Django的搜索引擎集成框架
from haystack . forms import SearchForm
# 创建日志记录器, 日志名称与当前模块一致( __name__) , 便于定位日志来源( 区分其他模块日志)
logger = logging . getLogger ( __name__ )
# 定义自定义搜索表单类BlogSearchForm, 继承自Haystack提供的SearchForm( 基础搜索表单)
# 作用: 扩展Haystack默认搜索表单, 添加自定义字段和搜索逻辑
class BlogSearchForm ( SearchForm ) :
# 定义搜索输入字段: querydata( 搜索关键词字段)
# required=True: 表示该字段为必填项, 用户必须输入关键词才能提交搜索
# CharField: 单行文本输入框, 适合接收搜索关键词
querydata = forms . CharField ( required = True )
# 重写父类的search方法, 自定义搜索逻辑( 保留父类核心功能, 添加日志记录)
def search ( self ) :
# 1. 调用父类( SearchForm) 的search方法, 执行Haystack默认搜索流程
# 父类会自动处理索引查询、关键词匹配等核心逻辑, 返回搜索结果集( SearchQuerySet对象)
datas = super ( BlogSearchForm , self ) . search ( )
# 2. 验证表单数据是否合法( 根据字段定义的规则, 如required=True)
if not self . is_valid ( ) :
# 若表单数据不合法( 如未输入关键词) , 调用父类的no_query_found方法返回默认空结果
return self . no_query_found ( )
# 3. 若表单验证通过, 获取清理后的搜索关键词( cleaned_data是Django表单验证后的安全数据字典)
if self . cleaned_data [ ' querydata ' ] :
# 记录搜索日志:将用户输入的关键词写入日志(便于统计热门搜索、排查问题)
logger . info ( self . cleaned_data [ ' querydata ' ] )
# 4. 返回搜索结果集( datas) , 该结果集会传递给搜索结果页面模板进行渲染
return datas