构建一个表单
导入模块
from django import forms from django.forms import widgets from django.core.exceptions import ValidationError
创建form类
from django import forms from django.forms import widgets from django.core.exceptions import ValidationError import re from django.contrib.auth.models import User class LoginForm(forms.Form): # 字段名字(username)就是渲染后input标签的name属性 username = forms.CharField(min_length=2, max_length=8, strip=True, # 是否移除用户输入空白 # error_messages 为错误触发的错误信息 error_messages={"required": "该字段不能为空", "min_length": "用户名长度不能小于2", "max_length": "用户名长度不能大于8"}, # 给input添加属性 widget=widgets.TextInput(attrs={ "class": "form-control", "placeholder": "2-8 位中文/字母/下划线", "id": "inputname"})) password = forms.CharField(min_length=6,max_length=20, strip=True, error_messages={"required":"该字段不能为空", "min_length":"密码长度不能小于6位", "max_length":"密码长度不能大于20位"}, widget = widgets.PasswordInput(attrs={ "class":"form-control", "placeholder":"密码需6-20个字符", "id":"inputPassword3"})) check_pwd = forms.CharField(min_length=6,max_length=20, strip=True, error_messages={"required":"该字段不能为空", "min_length":"密码长度不能小于6位", "max_length":"密码长度不能大于20位"}, widget = widgets.PasswordInput(attrs={ "class":"form-control", "placeholder":"请再次输入密码", "id":"inputPassword4"})) email = forms.EmailField(error_messages={‘required‘: "邮箱不能为空", "invalid":"请输入有效的邮箱地址"}, widget = widgets.EmailInput(attrs={ "class":"form-control", "placeholder":"请输入邮箱", "id":"inputemail"}))
视图
from .forms import LoginForm def form_reg(request): if request.method == "POST": login_form = LoginForm(request.POST) # 将数据传给对应字段 绑定数据的表单实例 if login_form.is_valid(): # 判读是否全部通过验证 print("通过验证") print(login_form.cleaned_data) # 保存全部通过验证的表单数据 {‘username‘: ‘周军豪123‘, ‘password‘: ‘961023hao‘} username = login_form.cleaned_data.get("username") password = login_form.cleaned_data.get("password") User.objects.create_user(username=username, password=password) print("数据库保存成功") return redirect("/log_in/") else: errors = login_form.errors # 字典类型,键是字段名,值是一个存着所有错误信息的列表 莫版中用{{ errors.字段名.0 }} # print(type(login_form.errors))# <class ‘django.forms.utils.ErrorDict‘> # login_form.errors={"user":["小于5位","不是数字"],"pwd":["",""]} error_all = errors.get("__all__") #全局钩子的错误信息保存在了键是 __all__ 的值的列表中,在模版语言中用{{ error_all.0 }} print(error_all) return render(request, "form_reg.html", {"errors": errors, "error_all":error_all, "login_form": login_form}) else:
login_form = LoginForm() # form组件的实例对象 未绑定表单实例 GET请求时渲染出input标签
return render(request, "form_reg.html", {"login_form": login_form})
模版
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <!-- 新 Bootstrap 核心 CSS 文件 --> <link rel="stylesheet" href="//cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.css"> <style> .container{ margin-top: 100px; } </style> </head> <body> <div class="container"> <div class="row"> <div class="col-md-6"> <form action="/login/" method="post"> {% csrf_token %} <div class="form-group"> <label for="user">user</label> {{ login_form.user }} <span>{{ errors.user.0 }}</span> </div> <div class="form-group"> <label for="pwd">pwd</label> {{ login_form.pwd }} <span>{{ errors.pwd.0 }}</span> </div> <div class="form-group"> <label for="gender">gender</label> {{ login_form.gender }}<span>{{ error_all.0 }}</span> </div> <p>{{ login_form.usersss }}</p> <button type="submit" class="btn btn-default">Submit</button> </form> <hr>
{# <form action="">#} {# {{ login_form.as_p }}#} {# </form>#} </div> </div> </div> </body> </html>