版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_33689414/article/details/78396966
Django表单
GET方法请求处理
在testdjango项目中,创建一个search.py文件,文件内容:
from django.http import HttpResponse
from django.shortcuts import render_to_response
def search_from (requset) :
return render_to_response('search_from.html' )
def search (request) :
request.encoding = 'utf-8'
if 'q' in request.GET:
message = '你搜索的内容为:' + request.GET['q' ]
else :
message = '你提交了空表单'
return HttpResponse(message)
在templates目录下创建一个search_from.html的文件,文件内容:
<!DOCTYPE html>
<html lang ="en" >
<head >
<meta charset ="UTF-8" >
<title > Title</title >
</head >
<body >
<form action ="/search" method ="get" >
<input type ="text" name ="q" />
<input type ="submit" value ="搜索" />
</form >
</body >
</html >
在testmodel/urls.py文件下,配置url的路径:
urlpatterns = [
...
url(r'^search_from/' , search.search_from),
url(r'^search/' , search.search),
...
]
在浏览器中输入127.0.0.1:8000/search_from
,显示search_from.html的内容,在输入框中输入数据,显示如下:
点击提交,显示如下:
POST方法提交表单数据处理
在templates目录下创建一个search_from_post.html的文件,文件内容为:
<!DOCTYPE html>
<html lang ="en" >
<head >
<meta charset ="UTF-8" >
<title > Title</title >
</head >
<body >
<form action ="/search_post/" method ="post" >
{% csrf_token %}
<input type ="text" name ="q" />
<input type ="submit" value ="搜索" />
</form >
<p > {{ content }} </p >
</body >
</html >
备注:form表单的action,如果写成”/search_post”,会报错,如:
RuntimeError at /search_post
You called this URL via POST, but the URL doesn't end in a slash and you have APPEND_SLASH set . Django can't redirect to the slash URL while maintaining POST data. Change your form to point to 127.0 .0 .1 :8000 /search_post/ (note the trailing slash), or set APPEND_SLASH=False in your Django settings.
写成”/search_post/”就好了。
在search.py文件创建一个方法search_from_post
,如:
from django.shortcuts import render
def search_from_post (request) :
context = {}
context['content' ] = ''
if request.POST:
context['content' ] = request.POST['q' ]
print(context)
return render(request=request, template_name='search_from_post.html' , context=context)
在项目的urls.py文件,配置url,如:
urlpatterns = [
...
url(r'^search_post/' , search.search_from_post),
...
]
在浏览器中输入127.0.0.1:8000/search_post/
,显示:
在输入框输入王者荣耀,点击搜索,显示