django 补充和中间件

配置

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
基于form组件的钩子函数登陆验证
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必须有返回值

 

原文地址:https://www.cnblogs.com/pythonclass/p/7793240.html