from组件补充

时间:2022-10-03 03:22:16

一、定义的规则

class TeacherForm(Form):  #必须继承Form
# 创建字段,本质上是正则表达式
username = fields.CharField(
required=True, #必填字段
error_messages={"required":"用户名不能为空!!"}, #显示中文错误提示
widget=widgets.TextInput(attrs={"placeholder":"用户名","class":"form-control"}), #自动生成input框
label="姓名",
label_suffix=":"
)
password = fields.CharField(required=True, error_messages={'required': '密码不能为空'},
widget=widgets.PasswordInput(attrs={'placeholder': '密码', 'class': 'form-control'}),
label="密码",
label_suffix=":"
) # 不能为空 email = fields.EmailField(
required=True,
error_messages={"required":"邮箱不能为空!!","invalid":"无效的邮箱"},
widget=widgets.EmailInput(attrs={"placeholder": "邮箱", "class": "form-control"}), # 自动生成input框
label = "邮箱",
label_suffix = ":"
) #不能为空且邮箱格式要一致 页面上渲染

from组件补充

用第二种方式需要加上下面的这个:

from组件补充

 二、下拉框的规则

from组件补充

三、判断用户民是不存在,存在就不添加了

需要导入:

from django.core.exceptions import ValidationError

from组件补充

四、initial  修改时用到

from组件补充

五、自定义配置

1、在settings中:

from组件补充

2、导入settings

from django.conf import settings

3、使用

from组件补充

 六、多对多修改两种方式(用Form)
def editteacher(request,nid):
obj = models.UserInfo.objects.filter(id=nid, ut_id=1).first()
# print(obj.username)
if not obj:
return redirect("/teacherindex/")
if request.method=="GET":
print([obj.id for obj in obj.teacher_classes.all()]) #[2] 拿到select框的id是为了要做默认显示的
form = TeacherForm(initial={"username":obj.username,"password":obj.password,"email":obj.email,"teacher_classes":[obj.id for obj in obj.teacher_classes.all()]}) #就让显示一个input框,并且带有原来哪一行的内容
return render(request, "editteacher.html", {"form":form})
else:
form = TeacherForm(data=request.POST)
if form.is_valid():#开始校验,注意这要加括号
cls_list = form.cleaned_data.pop("teacher_classes")
print(cls_list)
models.UserInfo.objects.filter(id=nid).update(**form.cleaned_data)
obj.teacher_classes.set(cls_list) #更新第三张表
return redirect("/teacherindex/")
else:
return render(request, "editteacher.html", {"form":form}) 七、多对多添加(用Form)
def addteacher(request):
if request.method=="GET":
form = TeacherForm() #只是让显示一个input框
return render(request, "addteacher.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': 'ghf', 'password': '435', 'email': 'fddfg@qq.com', 'teacher_classes': ['4']}
cls_list = form.cleaned_data.pop("teacher_classes")
print("============id",cls_list)
form.cleaned_data['ut_id'] = 1
#创建新老师的对象
teacher_obj = models.UserInfo.objects.create(**form.cleaned_data)
#创建新老师和班级的关系
teacher_obj.teacher_classes.add(*cls_list) #以前添加的是对象,现在也可以吧id添加进去
return redirect("/teacherindex/")
else:
# print("=====?",form.errors,type(form.errors))#返回失败的结果
# print(form.errors["username"][0]) #拿到返回失败的结果,渲染到页面
return render(request, "addteacher.html", {"form":form})