Django Form和Ajax提交验证

Form验证

views.py

class LoginForm(Form):
    usr=fields.CharField(required=True,min_length=5,
                         error_messages={
                             'required':'不能为空',
                             'min_length':'不能小于5'
                         })
    pwd=fields.CharField(min_length=18)
    email=fields.EmailField(
        error_messages={
            'required': '不能为空',
            'invalid': '必须为邮箱格式'
        }
    )


def login(request):
    if request.method=='GET':
        return render(request,'login.html')
    else:
        obj=LoginForm(request.POST)
        if obj.is_valid():
            # print(obj.cleaned_data)
            return HttpResponse('ok')
        # else:
        #     print(obj.errors)
        return  render(request,'login.html',{'obj':obj})

login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Login</title>
</head>
<body>
<h1>Login</h1>
<form  action="/login/" method="post">
    {% csrf_token %}
    <p>
        user:<input type="text" name="usr">{{ obj.errors.usr.0 }}
    </p>
    <p>
        password:<input type="password" name="pwd">{{ obj.errors.pwd.0 }}
    </p>
    <p>
        email:<input type="text" name="email">{{ obj.errors.email.0 }}
    </p>
    <input type="submit" value="post">
</form>

</body>
</html>

Ajax验证,页面保留上一次数据

views.py

def ajax_login(request):
    import json
    ret={'status':True,'msg':None}
    obj=LoginForm(request.POST)
    if obj.is_valid():
        print((obj.cleaned_data))
    else:
        ret['status']=False
        ret['msg']=obj.errors
    v=json.dumps(ret)
    return HttpResponse(v)

login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Login</title>
</head>
<body>
<h1>Login</h1>
<form id="myform">
    {% csrf_token %}
    <p>
        user:<input type="text" name="usr">
    </p>
    <p>
        password:<input type="password" name="pwd">
    </p>
    <a οnclick="submitForm();">AjaxPost</a>
</form>
<script src="/static/jquery-3.2.1.min.js"></script>
<script>
    function submitForm() {
        $('.c1').remove();
        $.ajax({
            url: '/ajax_login/',
            type: 'POST',
            data: $('#myform').serialize(),
            dataType:'JSON',
            success: function (arg) {
                //console.log(arg);
                if(arg.status){

                }else {
                    $.each(arg.msg,function (index,value) {
                        //console.log(index,value);
                        var tag=document.createElement('span')
                        tag.innerHTML=value[0];
                        tag.className='c1';
                        $('#myform').find('input[name="'+index+'"]').after(tag);
                    })
                }
            }
        })
    }
</script>
</body>
</html>
发布了26 篇原创文章 · 获赞 0 · 访问量 588

猜你喜欢

转载自blog.csdn.net/kkLeung/article/details/105002534