需求
用戶提交form時,如果報錯,頁面中的用戶信息還在(除了密碼),沒有被刷新掉,不用用戶再次輸入。
速查
views.py
1
2
3
|
def
login(request):
obj
=
django表單生成文件.類(request.POST)
#創建form實例化,request.POST默認=空
return
render(request,
'請求的html'
,{
'obj'
:obj})
|
知識點
request.POST默認=空
html中form提交method="post"是小寫,Django中request.method判斷時候"POST"是大寫,因為Django自己調用了uper方法。
報錯刷新頁面時,實例化的form表單中應該有數據,即request.POST
詳細
1、准備一個Django-form登錄框
path
templates/login.html
1
2
3
4
5
|
<
form
action
=
"/login/"
method
=
"post"
>
<
p
>{{ obj.username }}</
p
>
<
p
>{{ obj.password }}</
p
>
<
input
type
=
"submit"
value
=
"submit"
/>
</
form
>
|
app01/forms/account.py
1
2
3
4
5
|
from
django
import
forms
class
LoginForm(forms.Form):
username
=
forms.CharField()
password
=
forms.CharField(widget
=
forms.PasswordInput())
|
app01/views/account.py
1
2
3
4
5
|
from
app01.forms
import
account as AccountForm
def
login(request):
obj
=
AccountForm.LoginForm()
return
render(request,
'account/login.html'
,{
'obj'
:obj})
|
2、進一步演化
請求發送后,form表單中有了提交的所有數據,如果報錯,會把所有提交的信息返回原來的頁面中,不用再次輸入。
app01/views/account.py
1
2
3
4
5
6
|
def
login(request):
if
request.method
=
=
'POST'
:
input_obj
=
AccountForm.LoginForm(request.POST)
return
render(request,
'account/login.html'
,{
'obj'
:input_obj})
obj
=
AccountForm.LoginForm()
return
render(request,
'account/login.html'
,{
'obj'
:obj})
|
3、代碼簡化
默認request.POST為空,當提交請求時,obj中就帶了提交的信息,返回頁面。
app01/views/account.py
1
2
3
4
5
|
def
login(request):
obj
=
AccountForm.LoginForm(request.POST)
if
request.method
=
=
'POST'
:
return
render(request,
'account/login.html'
,{
'obj'
:obj})
return
render(request,
'account/login.html'
,{
'obj'
:obj})
|