Django--form保存用户输入内容
需求
用户提交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}) |