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

第一种自定义

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

第二种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")

前端接收返回错误提示

django表单后端验证的三种思路及错误信息返回前端_第1张图片
image.png

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


django表单后端验证的三种思路及错误信息返回前端_第2张图片
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表单后端验证的三种思路及错误信息返回前端)