from django.shortcuts import render
from django import forms # Djingo的form模板模块
# Create your views here.
class LoginForm(forms.Form):
# 利用DjingoForm建立模板,它要继承forms.Form。
# 下面定义的变量名,必需和前端from表单中的 <input>的 name 属性一样才行!!!!
username = forms.CharField(max_length=6,
error_messages={"required": "用户名不能为空", "invalid": "格式错误", "max_length": "用户名过长"})
email = forms.EmailField(error_messages={"invalid": "格式错误", "required": "用户名不能为空"})
def login(request):
if request.method == "GET":
return render(request, "login.html")
elif request.method == "POST":
obj = LoginForm(request.POST) # 把request.post传给模板类,并实例化。
s = obj.is_valid() # 去OBJ里取值,并一个个的进行验证,只有全部格式都对S将返回TRUE或False
print(s)
ok1 = obj.clean() # 拿到成功之后的值,只有全部成功才能拿到
print(ok1)
erro = obj.errors.as_json() # 拿错误信息 as_json()可以让错信息更加明确
print(erro)
# 注意: "code": "required"错误是空内容,invalid是格式错误,max_length长度错误
return render(request, "login.html")
上面是为了测试,开发时这样弄:
obj = LoginForm(request.POST)
if obj.is_valid():
ok1 = obj.clean()
print(ok1)
else:
erro = obj.errors.as_json()
print(erro)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="/static/js/jquery-3.4.1.min.js"></script>
</head>
<body>
<h1>Hello Djingo</h1>
<form action="" method="post">
{% csrf_token %}
<p><input type="text" name="username" placeholder="用户名"></p>
<p><input type="password" name="password" placeholder="密码"></p>
<p><input type="text" name="email" placeholder="邮箱"></p>
<input type="submit" value="提交">
<input type="button" value="Ajax提交">
</form>
</body>
</html>