环境同前篇django的文章。
注意:使用表单提交,注释掉settings.py中的中间件crsf。
vim /root/py3/django-test1/test3/test3/settings.py MIDDLEWARE_CLASSES = ( #'django.middleware.csrf.CsrfViewMiddleware', ... )
配置视图函数:
vim /root/py3/django-test1/test3/booktest/views.py def postTest1(request): return render(request,'booktest/postTest1.html') def postTest2(request): username = request.POST['uname'] userpasswd = request.POST['passwd'] usergender = request.POST.get('ugender') userhobby = request.POST.getlist('uhobby') context = {'uname':username,'upwd':userpasswd,'ugender':usergender,'uhobby':userhobby} return render(request,'booktest/postTest2.html',context)
添加html模板:
vim /root/py3/django-test1/test3/templates/booktest/postTest1.html <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://×××w.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Title</title> </head> <body> <form method="post" action="/booktest/postTest2/"> 用户名:<input type="text" name="uname"><br> 密码:<input type="password" name="upasswd"><br> 性别:<input type="radio" name="ugender" value="男" checked="checked">男<input type="radio" name="ugender" value="女">女<br> 爱好:<input type="checkbox" name="uhobby" value="健身">健身 <input type="checkbox" name="uhobby" value="篮球">篮球 <input type="checkbox" name="uhobby" value="滑雪">滑雪 <br> <input type="submit" value="提交"> </form> </body> </html>
注意:html表单中的所有input元素的name属性会作为键,value属性会作为值,提交后传递给后端request.POST['键']来接收。
vim /root/py3/django-test1/test3/templates/booktest/postTest2.html <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://×××w.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Title</title> </head> <body> 用户名:{{ uname }}<br> 密码:{{ upwd }}<br> 性别:{{ ugender }}<br> 爱好:{{ uhobby }}<br> {% for hobby in uhobby %} {{ hobby }} {% endfor %} </body> </html>
配置应用的url:
vim /root/py3/django-test1/test3/booktest/urls.py from django.conf.urls import url from . import views urlpatterns = [ ... url(r'postTest1/$',views.postTest1), url(r'postTest2/$',views.postTest2), ]
启动web服务:
cd /root/py3/django-test1/test3/ python manage.py runserver 192.168.255.70:8000
浏览器访问:http://192.168.255.70:8000/booktest/postTest1/
填写表单:
填写表单,点击提交,浏览器url变为:http://192.168.255.70:8000/booktest/postTest2/
可以打开浏览器开发者调试模式,查看表单数据:
演示完成。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。