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.
Django/doc/blog/forms.py

38 lines
2.2 KiB

This file contains ambiguous Unicode characters!

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库导入基础搜索表单类SearchFormHaystack是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