Python - Django - form 组件基本用法
普通 form 表单的处理:
reg.html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>注册页面</title> </head> <body> <form action="/reg/" method="post"> {% csrf_token %} <p>用户名: <input type="text" name="username"> <span>{{ error.user }}</span> {# 如果有错误,就获取错误信息 #} </p> <p>密码: <input type="password" name="pwd"> <span>{{ error.pwd }}</span> {# 如果有错误,就获取错误信息 #} </p> <p> <input type="submit"> </p> </form> </body> </html>
views.py:
from django.shortcuts import render, HttpResponse from app01 import models def reg(request): error = {"user": "", "pwd": ""} # 用一个字典来存错误信息 if request.method == "POST": username = request.POST.get("username") password = request.POST.get("pwd") if len(username) > 5: error["user"] = "用户名不能大于 5 位" if len(password) < 6: error["pwd"] = "密码不能小于 6 位" elif len(password) > 10: error["pwd"] = "密码不能大于 10 位" return render(request, "reg.html", {"error": error})
访问,http://127.0.0.1:8000/reg/
输入大于 5 位数的用户名和大于 10 位数的密码
使用 form 组件处理表单:
reg2.html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>注册页面</title> </head> <body> <form action="/reg2/" method="post" novalidate> {% csrf_token %} {{ form_obj.as_p }} {# 以 p 标签形式显示 #} {# {{ form_obj.errors.username }} {# 单独获取 username 的错误信息 #} {# {{ form_obj.errors.password }} {# 单独获取 password 的错误信息 #} <p><input type="submit"></p> </form> </body> </html>
form_obj 可以直接获取到 username、password 的错误信息,也可以通过 errors 来单独获取
views.py:
from django.shortcuts import render, HttpResponse from app01 import models from django import forms # 导入 form 组件 # 定义一个 form 类 class RegForm(forms.Form): username = forms.CharField( min_length=5, label="用户名", # 设置标签名 # 错误信息 error_messages={ "min_length": "用户名不能大于5位!", } ) password = forms.CharField( min_length=6, label="密码", # 设置标签名 # 错误信息 error_messages={ "min_length": "密码不能少于6位!", } ) def reg2(request): form_obj = RegForm() # GET 请求,实例化 form 对象 if request.method == "POST": form_obj = RegForm(request.POST) # form 帮我们做校验 if form_obj.is_valid(): # 判断 form_obj 是否有值 pass return render(request, "reg2.html", {"form_obj": form_obj})
访问,http://127.0.0.1:8000/reg2/
如果要把密码处的内容隐藏起来,要用到 widgets
views.py:
from django import forms from django.forms import widgets class RegForm(forms.Form): username = forms.CharField( min_length=5, label="用户名", error_messages={ "min_length": "用户名不能大于5位!", } ) password = forms.CharField( min_length=6, label="密码", error_messages={ "min_length": "密码不能少于6位!", }, widget=widgets.PasswordInput() # 把输入的密码隐藏起来 )
运行结果:
但是点击 “提交” 之后
密码的内容没有了
修改 views.py,在 PasswordInput 中添加参数:
from django import forms from django.forms import widgets class RegForm(forms.Form): username = forms.CharField( min_length=5, label="用户名", error_messages={ "min_length": "用户名不能大于5位!", } ) password = forms.CharField( min_length=6, label="密码", error_messages={ "min_length": "密码不能少于6位!", }, widget=widgets.PasswordInput(render_value=True) )
运行结果: