天天看点

django关于在前端中添加搜索功能的方法

django关于在前端中添加搜索功能的方法

  • 首先需要在url.py中定义路由:
  • 定义好路由之后,在对应app中的 views.py 编写逻辑代码:
def pdaq_search(request, ):
    if request.method == 'GET':
        pdaq_ip = request.GET.get('pdaq_ip', '')
        try:
            pdaq_isinstant = Message.objects.get(IP地址__icontains=pdaq_ip)
            # print('******************', pdaq_isinstant)
            # if pdaq_isinstant:
            context = {
                'pdaq_isinstant': pdaq_isinstant,
            }
            return render(request, 'detail.html', context=context)
        except Exception as search_error:
            print(search_error)
           

** 这里重点说一下,这其中

pdaq_ip = request.GET.get('pdaq_ip', '')

这句代码中的参数名称和你前端 HTML 文档中 input 标签中的 name 属性相关,当你name属性中定义了什么名字,则在该语句中传入什么参数 **

  • 到这步后端需要写的东西基本都已经完成,下一步则需要在 HTML 中编写相关的东西
  • 首先是先在首页中编写搜索框,直接上代码:
<form role="search" method="get" id="searchform" action="search_pdaq/">
	<input type="search" name="pdaq_ip" placeholder="搜索" value="{{ pdaq_ip }}">
<button type="submit"><span class="ion-ios-search-strong">搜索</span></button>
</form>
           
  • 这里定义好以后,你在前端搜索框中的东西,就会根据 action 属性中填写的 url 将请求传递到后端,上面的 get 方法,则可以获取到你在表单中填入的数据,至此已经查询到你需要得到的数据了
  • 接下来,你需要新建一个 HTML 文件,然后将查询到的数据,通过 render 方法,将数据返回到客户端,显示给用户