美文网首页
django表单后端验证的三种思路及错误信息返回前端

django表单后端验证的三种思路及错误信息返回前端

作者: hugoren | 来源:发表于2018-04-24 11:07 被阅读0次

    第一种自定义

     获取到表单的数据,自写校验规则
    

    第二种form插件的方式

    定义校验类

    class UserForm(forms.Form):
        username = forms.CharField(label="用户名", error_messages={"required": "用户名必填"})
        password = forms.CharField(label="密码", error_messages={"required": "密码必填"})
        sms_code = forms.CharField(label="验证码", error_messages={"required": "验证码必填"})
    
    

    使用校验类

    @csrf_exempt
    def login_handler(req):
        if req.method == "POST":
            user_form = UserForm(req.POST)
            if user_form.is_valid():
                user_obj = user_form.cleaned_data
                is_auth = authenticate(username=user_obj.get("username"), password=user_obj.get("password"))
                if is_auth and is_auth.is_active:
                    login(req, is_auth)
                    return HttpResponseRedirect('/')
                else:
                    return render(req, "login.html", {"retcode": 1, "stderr": "用户名或密码不正确"})
            else:
                return render(req, "login.html", {"retcode": 1, "stderr": user_form.errors})
        else:
            return HttpResponseRedirect("/login")
    
    

    前端接收返回错误提示

    image.png

    错误信息放在form之中,否则不会有提示


    image.png

    使用schedule等第三方的库

    marshmallow-code/marshmallow

    from datetime import date
    from marshmallow import Schema, fields, pprint
    
    class ArtistSchema(Schema):
        name = fields.Str()
    
    class AlbumSchema(Schema):
        title = fields.Str()
        release_date = fields.Date()
        artist = fields.Nested(ArtistSchema())
    
    bowie = dict(name='David Bowie')
    album = dict(artist=bowie, title='Hunky Dory', release_date=date(1971, 12, 17))
    
    schema = AlbumSchema()
    result = schema.dump(album)
    pprint(result.data, indent=2)
    # { 'artist': {'name': 'David Bowie'},
    #   'release_date': '1971-12-17',
    #   'title': 'Hunky Dory'}
    

    相关文章

      网友评论

          本文标题:django表单后端验证的三种思路及错误信息返回前端

          本文链接:https://www.haomeiwen.com/subject/qhwdlftx.html