理解表单类:上一篇中讲到了用户登录代码实现,用户登录框可以用HTML代码实现或者是表单实现。
在.个人的app下创建forms.py(这里很多人会写成from)
这个文件是专门存放各种与表单有关的类。
class Foo(Form): #必须继承
username = xxx
password = xxx
email = xxx
注意这里的字段必须和input的name字段一致
from django.forms import Form
from django.forms import fields
from django.forms import widgets
from django.shortcuts import render,redirect
from app01 import models
# Create your views here.
from django.forms import Form
from django.forms import fields
from django.forms import widgets
# 1、创建规则
class TeacherForm(Form): #必须继承Form
# 创建字段,本质上是正则表达式
username = fields.CharField(
required=True, #必填字段
error_messages={"required":"用户名不能为空!!"}, #显示中文错误提示
widget=widgets.TextInput(attrs={"placeholder":"用户名","class":"form-control"}) #自动生成input框
)
password = fields.CharField(required=True, error_messages={'required': '密码不能为空'},
widget=widgets.TextInput(attrs={'placeholder': '密码', 'class': 'form-control'})) # 不能为空
email = fields.EmailField(
required=True,
error_messages={"required":"邮箱不能为空!!","invalid":"无效的邮箱"},
widget=widgets.EmailInput(attrs={"placeholder": "邮箱", "class": "form-control"}) # 自动生成input框
) #不能为空且邮箱格式要一致
# 2、使用规则:将数据和规则进行匹配
def teacherindex(request):
teacher_obj = models.UserInfo.objects.all()
# print(teacher_obj)
return render(request,"teacherindex.html",{"teacher_obj":teacher_obj})
def add(request):
if request.method=="GET":
form = TeacherForm() #只是让显示一个input框
return render(request,"add.html",{"form":form })
else:
form = TeacherForm(data=request.POST)
# print(form) #<QuerySet [<UserInfo: UserInfo object>, <UserInfo: UserInfo object>, <UserInfo: UserInfo object>]>
if form.is_valid():# 开始验证
# print('执行成功',form.cleaned_data) # 所有匹配成功,字典
# {'username': 'asd', 'password': 'sdf', 'email': 'sadf@live.com','ut_id':1}
form.cleaned_data['ut_id'] = 1 #要分的清是班主任还是讲师
models.UserInfo.objects.all().create(**form.cleaned_data)
return redirect("/teacherindex/")
else:
# print("=====?",form.errors,type(form.errors))#返回失败的结果
# print(form.errors["username"][0]) #拿到返回失败的结果,渲染到页面
return render(request,"add.html",{"form":form})
或者是下面的方法:
from django import forms
class LoginForm(form.Form): # 记住格式
username = forms.CharField()
password = forms.CharField(widget=forms.PasswordInput)
# 实例化看下效果
login_form = LoginForm()
print(login_form)
<tr><th><label for='id_username'>Usernaem:</label></th><td>
<input id='id_username' name='username' type='text' requuired/></td></tr>
值得注意的是form表单里面的类和前段页面的name是相同的,因为不需要看前段模板也可以生成HTML页面
上面这个实例化类里面没有传递任何数据,得到的是HTML代码,我们可以认为不管是前端的表单,还是后端的表单类,都是对象,这个对象的属性就是表单中的对话框(input)