当前位置:Gxlcms > 数据库问题 > [oldboy-django][2深入django]form表单clean_xx, clean完成数据验证+ form错误信息

[oldboy-django][2深入django]form表单clean_xx, clean完成数据验证+ form错误信息

时间:2021-07-01 10:21:17 帮助过:30人阅读

需求 后台生成form里面的input标签,并设置input标签的属性, class RegisterForm(Form): email = fields.EmailField() password = fields.CharField() password2 = fields.CharField() code = fields.CharField() avatar = fields.FileField(widget=widgets.FileInput(attrs={id: inputAvatar})) def register(request): if request.method == GET: obj = RegisterForm() return render(request, register.html, {obj: obj}) <form method="POST" action="/register/" enctype="multipart/form-data"> {% csrf_token %} {{ obj.avatar }} {{ obj.usernam }} </form> View Code

向在form里面获取session值,即传递request参数

技术分享图片
# form标签向获取request里面的值--重写__init__函数
    def __init__(self, request, *args, **kwargs):
        self.request = request
        super(RegisterForm, self).__init__(*args, **kwargs)
View Code


form验证某个字段 self.clean_字段名

技术分享图片
# form标签验证某个字段
    def clean_code(self):
    input_code = self.cleaned_data.get(code)
    session_code = self.request.session.get(code)  # 请查看check_code函数
    if input_code != session_code:
        raise ValidationError(验证码错误)
    else:
        return input_code
    # self.errors = {‘code‘: [‘验证码错误‘], ‘xx‘:[错误1,错误2]}
View Code


form验证多个字段 self.clean

技术分享图片
# form标签联合数据验证
    def clean(self):
    """
    此时,已经拿到所有的input值,对两次输入密码进行验证
    """
    p1 = self.cleaned_data.get(password1)
    p2 = self.cleaned_data.get(password2)
    if p1 != p2:
        raise ValidationError(两次输入密码不一致) # 默认放到self.errors[‘__all__‘]里面
    else:
        return self.cleaned_data
        # return None
    """
    self.errors = {‘__all__‘: [‘两次输入密码不一致‘], ‘xx‘:[错误1,错误2]}
    NON_FIELD_ERRORS = ‘__all__‘   前台获取需要用到
    此时前端获取该错误; obj.non_field_errors
    """
View Code


form验证多个字段 self.clean 指明错误信息的Key,方便前端使用

技术分享图片
# 对整体错误的其他设置
    def clean(self):

        if p1 != p2:
            self.add_error(password2, 两次输入密码不一致)
            # 此时不用抛出异常了,因为抛出异常
            # 抛出异常也是执行self.add_error
            return None
        else:
            return self.cleaned_data

    此时在前端显示该错误: obj.errors.password2
View Code


form 的错误信息self.errors

技术分享图片
# form标签数据验证错误信息
    self.errors = {username:[错误1, 错误2], password: [错误1, 错误2]}
    def clean_xx(self) 如果遇到错,放到self.errors[xx]里面
    def clean(self) 如果遇到错,放到self.errors[__all__]里面

    但是如果要前端获取self.errors[__all__]错误,obj.errors.__all__是拿不到的
    而是obj.non_field_errors, 不是self.errors.non_fields_errors
View Code


注册form

技术分享图片
# 完整的forms.py
    # -*- coding: utf-8 -*-
    from django.forms import Form, fields, widgets
    from django.core.exceptions import ValidationError


    class RegisterForm(Form):
        username = fields.CharField(widget=widgets.TextInput(
            attrs={class: "form-control"}
        ))
        password = fields.CharField(widget=widgets.PasswordInput(
            attrs={class: "form-control"}
        ))
        password2 = fields.CharField(widget=widgets.PasswordInput(
            attrs={class: "form-control"}
        ))
        code = fields.CharField(widget=widgets.TextInput(
            attrs={class: "form-control"}
        ))
        avatar = fields.FileField(widget=widgets.FileInput(attrs={id: inputAvatar}))

        def __init__(self, request, *args, **kwargs):
            self.request = request
            super(RegisterForm, self).__init__(*args, **kwargs)

        def clean_code(self):
            input_code = self.cleaned_data.get(code).upper()
            session_code = self.request.session.get(code).upper()  # 请查看check_code函数
            if input_code != session_code:
                raise ValidationError(验证码错误)
            else:
                return input_code
            # self.errors = {‘code‘: [‘验证码错误‘], ‘xx‘:[错误1,错误2]}

        def clean(self):
            """
            此时,已经拿到所有的input值,对两次输入密码进行验证
            """
            p1 = self.cleaned_data.get(password)
            p2 = self.cleaned_data.get(password2)
            if p1 != p2:
                self.add_error(password2, 两次输入密码不一致) # 此时不用抛出异常了,因为抛出异常
                # 抛出异常也是执行self.add_error
                return None
                # raise ValidationError(‘两次输入密码不一致‘)
                #  默认放到self.errors[‘__all__‘]里面
                #  执行的是self.add_error(‘__all__‘, ‘两次输入密码不一致‘)
            else:
                return self.cleaned_data

    """
    self.errors = {‘__all__‘: [‘两次输入密码不一致‘], ‘xx‘:[错误1,错误2]}
    NON_FIELD_ERRORS = ‘__all__‘   前台获取需要用到
    """
View Code

 

[oldboy-django][2深入django]form表单clean_xx, clean完成数据验证+ form错误信息

标签:htm   init   合数   username   需求   one   widgets   render   csrf   

人气教程排行