django表单
get方法
在HelloWorld/HelloWorld下创建search.py
注意:中文前面的'u'
#-*- 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 = u'你搜索的内容为:' + request.GET['q']
else:
message = u'你提交了空表单'
return HttpResponse(message)
在模板目录templates中添加search_form.html表单
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>测试</title>
</head>
<body>
<form action="/search" method = "get">
<input type = 'text' name = "q">
<input type = 'submit" value = "搜索">
</form>
</body>
</html>
修改url.py
from django.conf.urls import *
from django.contrib import admin
from django.http import HttpResponse
from . import view,testdb,search #修改
urlpatterns = [
url(r'^$',view.hello),
url(r'^testdb$',testdb.testdb),
url(r'^search-form$',search.search-form), #新增
url(r'^search$',search.search), #新增
]
访问search-form页面
注意地址:http://127.0.0.1:8000/search-form,末尾千万别加 .html ,不然会报找不到资源
随便输入搜索
post方法
创建模板
在templates下创建post.html
{{ % csrf_token %}}标签 ,csrf全称:Cross Site Request Forgery ,是Django预防伪装提交功能,post提交的表格必须有这个标签
{{ rlt }}是表格处理结果预留位
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>测试post</title>
</head>
<body>
<form action="/search-post" method = "post">
{% csrf_token %}
<input type = "text" name = "q">
<input type = "submit" value = "Submit">
</form>
<p>{{ rlt }}</p>
</body>
</html>
创建控制器
在HelloWorld/HelloWorld下创建search2.py
# -*- coding:utf-8 -*-
from django.shortcuts import render
from django.views.decorators import csrf
#接收POST请求数据
def search_post(request):
ctx = {}
if request.POST:
ctx['rlt'] = request.POST['q']
return render(request,"post.html",ctx)
修改视图
修改urls.py
增加导入,增加匹配
# -*- coding:utf-8 -*-
from django.conf.urls import url
from django.contrib import admin
from django.http import HttpResponse
from . import view,testdb,search,search2
urlpatterns = [
url(r'^$',view.hello),
url(r'^testdb$',testdb.testdb),
url(r'^search-form$',search.search_form),
url(r'^search$',search.search),
url(r'^search-post$',search2.search_post),
]
访问页面
http://127.0.0.1:8000/search-post
是否已发现规律:url里的字段是urls.py表里 r^$ 中间的字段,
后面的search2是控制器代码search2.py,search_post是search2.py里的一个方法,
至于模板post.html在控制器代码search2.py里关联到了“ return render(request,"post.html",ctx)
”
随便输入提交