溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

django之瀏覽器使用POST提交表單,后端獲取數(shù)據(jù)

發(fā)布時(shí)間:2020-07-29 14:58:31 來源:網(wǎng)絡(luò) 閱讀:967 作者:crystaleone 欄目:開發(fā)技術(shù)

環(huán)境同前篇django的文章。


注意:使用表單提交,注釋掉settings.py中的中間件crsf。

vim /root/py3/django-test1/test3/test3/settings.py

MIDDLEWARE_CLASSES = (
    #'django.middleware.csrf.CsrfViewMiddleware',
    ...
)

配置視圖函數(shù):

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屬性會(huì)作為鍵,value屬性會(huì)作為值,提交后傳遞給后端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>


配置應(yīng)用的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),
]

啟動(dòng)web服務(wù):

cd /root/py3/django-test1/test3/
python manage.py runserver 192.168.255.70:8000

瀏覽器訪問:http://192.168.255.70:8000/booktest/postTest1/

填寫表單:

django之瀏覽器使用POST提交表單,后端獲取數(shù)據(jù)

填寫表單,點(diǎn)擊提交,瀏覽器url變?yōu)椋篽ttp://192.168.255.70:8000/booktest/postTest2/

可以打開瀏覽器開發(fā)者調(diào)試模式,查看表單數(shù)據(jù):

django之瀏覽器使用POST提交表單,后端獲取數(shù)據(jù)

演示完成。


向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI