html表单是网站交互性的经典方式。 本章将介绍如何用django对用户提交的表单数据进行处理。
http协议以"请求-回复"的方式工作。客户发送请求时,可以在请求中附加数据。服务器通过解析请求,就可以获得客户传来的数据,并根据url来提供特定的服务。
我们在之前的项目中创建一个 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'].encode('utf-8')
else:
message = '你提交了空表单'
return httpresponse(message)
在模板目录template中添加 search_form.html 表单:
<html>
<head>
<meta charset="utf-8" />
<title>search - w3cschool.cn</title>
</head>
<body>
<form action="/search/" method="get">
<input type="text" name="q">
<input type="submit" value="search">
</form>
</body>
</html>
urls.py 规则修改为如下形式:
from django.conf.urls import *
from helloworld.view import hello
from helloworld.testdb import testdb
from helloworld import search
urlpatterns = patterns("",
('^hello/$', hello),
('^testdb/$', testdb),
(r'^search-form/$', search.search_form),
(r'^search/$', search.search),
)
访问地址:http://192.168.45.3:8000/search-form/并搜索,结果如下所示:
上面我们使用了get方法。视图显示和请求处理分成两个函数处理。
提交数据时更常用post方法。我们下面使用该方法,并用一个url和处理函数,同时显示视图和处理请求。
我们在tmplate 创建 post.html:
<html>
<head>
<meta charset="utf-8" />
<title>search - w3cschool.cn</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>
在模板的末尾,我们增加一个rlt记号,为表格处理结果预留位置。
表格后面还有一个{% csrf_token %}的标签。csrf全称是cross site request forgery。这是django提供的防止伪装提交请求的功能。post方法提交的表格,必须有此标签。
在helloworld目录下新建 search2.py 文件并使用 search_post 函数来处理 post 请求:
# -*- coding: utf-8 -*-
from django.shortcuts import render
from django.core.context_processors import csrf
# 接收post请求数据
def search_post(request):
ctx ={}
ctx.update(csrf(request))
if request.post:
ctx['rlt'] = request.post['q']
return render(request, "post.html", ctx)
urls.py 规则修改为如下形式:
from django.conf.urls import *
from helloworld.view import hello
from helloworld.testdb import testdb
from helloworld import search
from helloworld import search2
urlpatterns = patterns("",
('^hello/$', hello),
('^testdb/$', testdb),
(r'^search-form/$', search.search_form),
(r'^search/$', search.search),
(r'^search-post/$', search2.search_post),
)
访问 http://192.168.45.3:8000/search-post/ 显示结果如下:
完成以上实例后,我们的目录结构为:
helloworld
|-- helloworld
| |-- __init__.py
| |-- __init__.pyc
| |-- models.pyc
| |-- search.py
| |-- search.pyc
| |-- search2.py
| |-- search2.pyc
| |-- settings.py
| |-- settings.pyc
| |-- testdb.py
| |-- testdb.pyc
| |-- urls.py
| |-- urls.pyc
| |-- view.py
| |-- view.pyc
| |-- wsgi.py
| `-- wsgi.pyc
|-- testmodel
| |-- __init__.py
| |-- __init__.pyc
| |-- admin.py
| |-- models.py
| |-- models.pyc
| |-- tests.py
| `-- views.py
|-- manage.py
`-- templates
|-- base.html
|-- hello.html
|-- post.html
`-- search_form.html
3 directories, 29 files
每个view函数的第一个参数是一个httprequest对象,就像下面这个hello()函数:
from django.http import httpresponse
def hello(request):
return httpresponse("hello world")
httprequest对象包含当前请求url的一些信息:
| 属性 | 描述 |
| path | 请求页面的全路径,不包括域名—例如, "/hello/"。 |
| method | 请求中使用的http方法的字符串表示。全大写表示。例如: if request.method == 'get': |
| get | 包含所有http get参数的类字典对象。参见querydict 文档。 |
| post | 包含所有http post参数的类字典对象。参见querydict 文档。 服务器收到空的post请求的情况也是有可能发生的。也就是说,表单form通过http post方法提交请求,但是表单中可以没有数据。因此,不能使用语句if request.post来判断是否使用http post方法;应该使用if request.method == "post" (参见本表的method属性)。 注意: post不包括file-upload信息。参见files属性。 |
| request | 为了方便,该属性是post和get属性的集合体,但是有特殊性,先查找post属性,然后再查找get属性。借鉴php's $_request。 例如,如果get = {"name": "john"} 和post = {"age": '34'},则 request["name"] 的值是"john", request["age"]的值是"34". 强烈建议使用get and post,因为这两个属性更加显式化,写出的代码也更易理解。 |
| cookies | 包含所有cookies的标准python字典对象。keys和values都是字符串。参见第12章,有关于cookies更详细的讲解。 |
| files | 包含所有上传文件的类字典对象。files中的每个key都是<input type="file" name="" />标签中name属性的值. files中的每个value 同时也是一个标准python字典对象,包含下面三个keys:
注意:只有在请求方法是post,并且请求页面中<form>有enctype="multipart/form-data"属性时files才拥有数据。否则,files 是一个空字典。 |
| meta | 包含所有可用http头部信息的字典。 例如:
meta 中这些头加上前缀http_最为key, 例如:
|
| user | 是一个django.contrib.auth.models.user 对象,代表当前登录的用户。 如果访问用户当前没有登录,user将被初始化为django.contrib.auth.models.anonymoususer的实例。 你可以通过user的is_authenticated()方法来辨别用户是否登录:
if request.user.is_authenticated():
# do something for logged-in users.
else:
# do something for anonymous users.
只有激活django中的authenticationmiddleware时该属性才可用 |
| session | 唯一可读写的属性,代表当前会话的字典对象。只有激活django中的session支持时该属性才可用。 参见第12章。 |
| raw_post_data | 原始http post数据,未解析过。 高级处理时会有用处。 |
request对象也有一些有用的方法:
| 方法 | 描述 |
|---|---|
| __getitem__(key) | 返回get/post的键值,先取post,后取get。如果键不存在抛出 keyerror。 这是我们可以使用字典语法访问httprequest对象。 例如,request["foo"]等同于先request.post["foo"] 然后 request.get["foo"]的操作。 |
| has_key() | 检查request.get or request.post中是否包含参数指定的key。 |
| get_full_path() | 返回包含查询字符串的请求路径。例如, "/music/bands/the_beatles/?print=true" |
| is_secure() | 如果请求是安全的,返回true,就是说,发出的是https请求。 |
在httprequest对象中, get和post属性是django.http.querydict类的实例。
querydict类似字典的自定义类,用来处理单键对应多值的情况。
querydict实现所有标准的词典方法。还包括一些特有的方法:
| 方法 | 描述 |
|---|---|
| __getitem__ | 和标准字典的处理有一点不同,就是,如果key对应多个value,__getitem__()返回最后一个value。 |
| __setitem__ | 设置参数指定key的value列表(一个python list)。注意:它只能在一个mutable querydict 对象上被调用(就是通过copy()产生的一个querydict对象的拷贝). |
| get() | 如果key对应多个value,get()返回最后一个value。 |
| update() | 参数可以是querydict,也可以是标准字典。和标准字典的update方法不同,该方法添加字典 items,而不是替换它们:
>>> q = querydict('a=1')
>>> q = q.copy() # to make it mutable
>>> q.update({'a': '2'})
>>> q.getlist('a')
['1', '2']
>>> q['a'] # returns the last
['2']
|
| items() | 和标准字典的items()方法有一点不同,该方法使用单值逻辑的__getitem__():
>>> q = querydict('a=1&a=2&a=3')
>>> q.items()
[('a', '3')]
|
| values() | 和标准字典的values()方法有一点不同,该方法使用单值逻辑的__getitem__(): |
此外, querydict也有一些方法,如下表:
| 方法 | 描述 |
|---|---|
| copy() | 返回对象的拷贝,内部实现是用python标准库的copy.deepcopy()。该拷贝是mutable(可更改的) — 就是说,可以更改该拷贝的值。 |
| getlist(key) | 返回和参数key对应的所有值,作为一个python list返回。如果key不存在,则返回空list。 it's guaranteed to return a list of some sort.. |
| setlist(key,list_) | 设置key的值为list_ (unlike __setitem__()). |
| appendlist(key,item) | 添加item到和key关联的内部list. |
| setlistdefault(key,list) | 和setdefault有一点不同,它接受list而不是单个value作为参数。 |
| lists() | 和items()有一点不同, 它会返回key的所有值,作为一个list, 例如:
>>> q = querydict('a=1&a=2&a=3')
>>> q.lists()
[('a', ['1', '2', '3'])]
|
|
urlencode() |
返回一个以查询字符串格式进行格式化后的字符串(e.g., "a=2&b=3&b=5"). |