post传参的键和值是怎么来的?
name属性作为键, value作为值。根据键作为值。
任务:实现用户注册,将注册后的信息显示在页面上。
(1)新建postTest.html页面。
表单中控件的name不写,不会被提交。value不写,会被提交。
细微不同的action值,提交后所生成的url地址是不一样的。
| action的值 | 提交后生成的url |
|---|---|
| /study/postTest2 | http://127.0.0.1:8000/study/postTest2/ |
| study/postTest2 | http://127.0.0.1:8000/study/postTest1/study/postTest2/ |
怎样获取提交后的数据呢?
(2)配置路由
path('postTest1/',views.postTest1),
(3)定义视图
def postTest1(request):
# 返回postTest1.html
return render(request,"study/postTest1.html")
(4)查看效果
输入数据,单击提交按钮提交后,将DEBUG = True后效果如下:
解决如下:
输入数据重新提交,效果如下:
(5)再次配置路由
path('postTest2/',views.postTest2),
(6)再次编写视图函数
def postTest2(request):
# 怎么获取post传参方式中传递的参数
# name = request.POST["uname"] #获取post传参方式中name为uname控件的值
# pwd = request.POST["upwd"]
# sex = request.POST["ugender"]
name = request.POST.get("uname") # 获取post传参方式中name为uname控件的值
pwd = request.POST.get("upwd")
sex = request.POST.get("ugender")
hobby = request.POST.getlist("uhobby")
context = {"name": name, "pwd": pwd, "sex": sex, "hobby": hobby}
return render(request, "study/postTest2.html", context)
(7)编写postTest2.html
用户名:{{ name }}
密码:{{ pwd }}
性别:{{ sex }}
爱好:{{ hobby }}
{% for h in hobby %}
{{ h }}
{% endfor %}
(8)查看效果
单击提交后,效果如下:



