“Django 连通Elasticsearch之前后台串联”的版本间的差异
来自CloudWiki
第52行: | 第52行: | ||
return HttpResponse(h) | return HttpResponse(h) | ||
</nowiki> | </nowiki> | ||
+ | |||
+ | ==测试== | ||
+ | 登录前台搜索页:http://10.0.0.30:8000/blog/search_form/ | ||
+ | |||
+ | [[文件:big1-25.png]] | ||
+ | |||
+ | 点击搜索: | ||
+ | |||
+ | [[文件:big1-26.png]] |
2019年9月19日 (四) 06:47的版本
前言
我们在Django 连通Elasticsearch、Django 连通Elasticsearch之创建表单中分别用Django框架 连通了后台的ES 和前台的表单,现在让我们把django的前后台连接起来,使得表单搜索的关键字 能直接进入后台ES查询,并显示结果
修改视图层
我们在表单的视图层文件 search.py 中,添加拥有查询ES的代码:
# -*- coding: utf-8 -*- from django.http import HttpResponse from django.shortcuts import render_to_response import traceback from elasticsearch import Elasticsearch from .ElasticObj import ElasticObj # 表单 def search_form(request): return render_to_response('search_form.html') # 提交后的接收请求数据 def search(request): obj = ElasticObj("ott1", "ott_type1") h = obj.Get_Data_By_Body("电视")#搜索电视 return HttpResponse(h)
添加表单参数
现在我们尝试将前台表单传过来的参数,传到ES中进行查询:
# -*- coding: utf-8 -*- from django.http import HttpResponse from django.shortcuts import render_to_response import traceback from elasticsearch import Elasticsearch from .ElasticObj import ElasticObj # 表单 def search_form(request): return render_to_response('search_form.html') # 提交后的接收请求数据 def search(request): request.encoding='utf-8' if 'q' in request.GET: obj = ElasticObj("ott1", "ott_type1") h = obj.Get_Data_By_Body(request.GET['q'])#搜索电视 #message = '你搜索的内容为: ' + request.GET['q'] else: h ="" return HttpResponse(h)
测试
登录前台搜索页:http://10.0.0.30:8000/blog/search_form/
点击搜索: