Django 连通Elasticsearch之创建表单
来自CloudWiki
HTML表单是网站交互性的经典方式。 本章将介绍如何用Django对用户提交的表单数据进行处理。
HTTP 请求
HTTP协议以"请求-回复"的方式工作。客户发送请求时,可以在请求中附加数据。服务器通过解析请求,就可以获得客户传来的数据,并根据URL来提供特定的服务。
GET 方法
视图层
我们在之前的项目中创建一个 search.py 文件,用于接收用户的请求:
tutorial/blog/search.py 文件代码:
# -*- coding: utf-8 -*- from django.http import HttpResponse from django.shortcuts import render_to_response # 表单 def search_form(request): return render_to_response('search_form.html') # 提交后的接收请求数据 def search(request): request.encoding='utf-8' if 'q' in request.GET: message = '你搜索的内容为: ' + request.GET['q'] else: message = '你提交了空表单' return HttpResponse(message)
模板层
在模板目录 templates 中添加 search_form.html 表单:
tutorial/templates/search_form.html 文件代码:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>菜鸟教程(runoob.com)</title> </head> <body> <form action="/blog/search" method="get"> <input type="text" name="q"> <input type="submit" value="搜索"> </form> </body> </html>
url层
urls.py 规则修改为如下形式:
tutorial/blog/urls.py 文件代码:
from django.conf.urls import url from . import views from . import search urlpatterns = [ # url(r'^api/list$', views.BlogView.as_view(), name='blog-list'), url(r'^api/$', views.hello), url(r'^search_form/$',search.search_form), url(r'^search/$',search.search) ]
访问地址 http://[虚拟机ip]:8000/blog/search_form 并搜索,结果类似如下所示:
参考文档: