服务器接收到http协议的请求后,系统会根据报文自动创建HttpRequest对象
视图处理函数的第1个参数必须是HttpRequest对象
下列属性除非特别说明,都是只读的
属性 | 类型 | 说明 |
---|---|---|
path | 字符串 | 请求页面的完整路径,不包含域名和参数部分 |
method | 字符串 | 请求方式:get、post |
encoding | 字符串 | 编码方式:None、utf-8 |
GET | QueryDict | get请求方式的所有参数 |
POST | QueryDict | post请求方式的所有参数 |
FILES | 字典 | 上传文件数据 |
COOKIES | 字典 | cookie数据 |
session | 字典 | session数据 |
可以通过chrome的调试工具查看上述属性
实例演练: 获到请求的path和methon信息
修改urls.py文件:url(r’^req/$’, views.req),
修改views.py文件:
def req(request):
path = request.path
method = request.method
ret = 'path:' + path + "
" + 'method:' + method
return HttpResponse(ret)
dict.get('键',默认值)
可简写为
dict['键']
dict.getlist('键',默认值)
<form action="/app/req/" method="post">
username <input type="text" name="username" value="zhang3"> <br>
password <input type="password" name="password" value="123"> <br>
<input type="submit">
</form>
def form(request):
return render(request, 'app/form.html')
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
# 'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
def req(request):
name = request.POST.get('username')
passwd = request.POST.get('password')
ret = 'name:' + name + "
" + 'passwd:' + passwd
return HttpResponse(ret)
<form action="/app/req/" method="post">
性别:
男<input type="radio" name="gender" value="男" checked/>
女<input type="radio" name="gender" value="女"/><br/>
爱好:
吃饭<input type="checkbox" name="hobby" value="吃饭" checked/>
睡觉<input type="checkbox" name="hobby" value="睡觉"/>
打豆豆<input type="checkbox" name="hobby" value="打豆豆" checked/><br>
址址:
<select name="address" id="">
<option value="ln" selected>辽宁省</option>
<option value="jl">吉林省</option>
</select> <br>
<input type="submit">
</form>
def req(request):
gender = request.POST.get('gender')
hobby = request.POST.getlist('hobby') # 爱好有多个值,返回一个list
address = request.POST.get('address')
ret = ""
for h in hobby:
ret += h + ", "
rets = 'hobby:' + ret + '
'
rets += 'gender:' + gender + '
' + 'address:' + address
return HttpResponse(rets)