配置
from django.conf import settings
form组件
from django.forms import Form
from django.forms import fields
from django.forms import widgets
form自定义规则
from django.core.validators import RegexValidator
钩子函数
from django.core.exceptions import ValidationError
数据源无法实施更新,重写构造方法
方式一(推荐):
class ClassForm(Form):
caption = fields.CharField(error_messages={'required':'班级名称不能为空'})
# headmaster = fields.ChoiceField(choices=[(1,'娜娜',)])
headmaster_id = fields.ChoiceField(choices=[])
def __init__(self,*args,**kwargs):
super().__init__(*args,**kwargs)
self.fields['headmaster_id'].choices = models.UserInfo.objects.filter(ut_id=2).values_list('id','username')
方式二:
from django.forms.models import ModelChoiceField
class ClassForm(Form):
caption = fields.CharField(error_messages={'required':'班级名称不能为空'})
# headmaster = fields.ChoiceField(choices=[(1,'娜娜',)])
headmaster_id = ModelChoiceField(queryset=models.UserInfo.objects.filter(ut_id=2))
用户登录
- form的字段可以定义正则表达式
password = fields.CharField(
required=True,
min_length=3,
max_length=18,
error_messages={
'required': '密码不能为空',
'min_length': '密码长度不能小于3',
'max_length': '密码长度不能大于18',
'invalid': '密码格式错误',
},
validators=[RegexValidator('\d+','只能是数字') ]
)
- 主动向form中添加错误信息
# form.add_error('password','用户名或密码错误')
form.add_error('password',ValidationError('用户名或密码错误'))
钩子函数
- clean_字段名
注意:
必须有返回值
只能拿自己当前字段值
raise ValidationError('xxx')

class LoginForm(Form): username = fields.CharField( required=True, min_length=3, max_length=18, error_messages={ 'required': '用户不能为空', 'min_length': '用户长度不能小于3', 'max_length': '用户长度不能大于18', } ) password = fields.CharField( required=True, min_length=3, max_length=18, error_messages={ 'required': '密码不能为空', 'min_length': '密码长度不能小于3', 'max_length': '密码长度不能大于18', 'invalid': '密码格式错误', }, validators=[RegexValidator('\d+','只能是数字') ] ) def clean_username(self): # ... user = self.cleaned_data['username'] is_exsit = models.UserInfo.objects.filter(username=user).count() if not is_exsit: raise ValidationError('用户名不存在') return user def clean_password(self): user = self.cleaned_data['username'] return user

def login(request): if request.method == "GET": form = LoginForm() return render(request,'login.html',{'form':form}) elif request.method =="POST": form = LoginForm(data=request.POST) if form.is_valid(): # 验证成功 user = models.UserInfo.objects.filter(**form.cleaned_data).first() if not user: # 用户名或密码错误 # form.add_error('password','用户名或密码错误') form.add_error('password',ValidationError('用户名或密码错误')) return render(request, 'login.html', {'form': form}) else: request.session[settings.SJF] = {'id':user.id, 'username':user.username} return redirect('/index/') else: # 验证失败 return render(request, 'login.html',{'form':form})
django中间件
- 中间件是什么?
- 返回值注意
- 做过什么:
- 用户登录
- 日志记录
- csrf
- session
- 权限管理***
settings中MIDDLEWARE配置路径,注意顺序

class MiddlewareMixin(object): def __init__(self, get_response=None): self.get_response = get_response super(MiddlewareMixin, self).__init__() def __call__(self, request): response = None if hasattr(self, 'process_request'): response = self.process_request(request) if not response: response = self.get_response(request) if hasattr(self, 'process_response'): response = self.process_response(request, response) return response
先执行第一个中间件类的process_request方法,不阻止默认返回None,若阻止,不返回None,执行此中间件类的process_response方法,注意,process_response必须有返回值
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
· dotnet 源代码生成器分析器入门
· ASP.NET Core 模型验证消息的本地化新姿势
· 对象命名为何需要避免'-er'和'-or'后缀
· 编程神器Trae:当我用上后,才知道自己的创造力被低估了多少
· 开发的设计和重构,为开发效率服务
· 从零开始开发一个 MCP Server!
· Ai满嘴顺口溜,想考研?浪费我几个小时
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密