zoukankan      html  css  js  c++  java
  • Django之ModelForm通过ajax用户登录验证

     

    1、views代码:

      

    from django.core.exceptions import ValidationError
    class JsonCustomEncoder(json.JSONEncoder):
        def default(self,field):
            if isinstance(field,ValidationError):
                return {'code':field.code,'messages':field.messages}
            else:
                return json.JSONEncoder.default(self,field)
    
    ret={'status':"false",'error':None,'data':None}
    def login(request):
        if request.method=='POST':
            obj = forms.loginForm(request.POST)
            if obj.is_valid():
                a=int(5)
                ret['status']="true"
                username = obj.cleaned_data['username']
                password = obj.cleaned_data['pwd']
                namefilter = models.User.objects.filter(username=username,pwd=password)
                request.session["username"]=obj.cleaned_data['username']
                request.session["is_login"]=True
                request.session.set_expiry(5)
                if namefilter:
                    # return HttpResponse(json.dumps(ret))
                    return HttpResponse(json.dumps(ret))
            else:
                # ret["status"]=False
                ret['error']=obj.errors
                result = json.dumps(ret,cls=JsonCustomEncoder)
                print(result)
                return HttpResponse(result)
        elif request.method=="GET":
            obj = forms.loginForm()
            return render(request,'login.html',{'form':obj})
        # return render(request,'login.html')



    def index(request):
    a=request.session.get("username")
    if not a:
    return redirect('/login/')
    return render(request,'index.html',{'a':a})
     

    froms.py

    class loginForm(forms.Form):
        username = fields.CharField(
            required=True,
            widget=widgets.TextInput(attrs={'placeholder': '请输入用户名','id':'username'}),
            min_length=6,
            max_length=12,
            error_messages={'required':'用户名不能为空'}
        )
        pwd = fields.CharField(
            widget=widgets.PasswordInput(attrs={'placeholder': '请输入密码','id':'pwd'}),
            required=True,
            min_length=6,
            max_length=12,
            error_messages={'required':'密码不能为空'}
        )
    
        def clean(self):
            username = self.cleaned_data.get('username')
            password = self.cleaned_data.get('pwd')
            c = models.User.objects.filter(username=username,pwd=password)
            if c:
                return self.cleaned_data
            else:
                self.add_error('pwd','用户名或密码不一致')
                return None

    login.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <form id="fm" method="post" action="/login/">
            {% csrf_token %}
            <p><label for="username">用户名:</label>{{ form.username }}</p>
            <p><label for="password">密码:</label>{{ form.pwd }}<span id="error" style="color: red"></span></p>
    {#         <input id="loginform" type="submit" value="提交"></input>#}
            <button id="submit" type="button">提交</button>
        </form>
    <script src="/static/jquery-3.2.1.min.js"></script>
    <script>
        $(function () {
            $('#submit').click(function () {
                $.ajax({
                    url:'/login/',
                    type:"POST",
                    data:$('#fm').serialize(),
                    success:function (data) {
                        arg = JSON.parse(data);
                        if(arg["status"]==="true"){
                            location.href="/index/"
                        }else if(arg["status"]==="false"){
    {#                        alert(arg["error"]["pwd"][0]);#}
                            var a=arg["error"]["pwd"][0];
    {#                        alert(a);#}
                            $("#error").text(a);
    
                        }
                    }
                })
            })
        })
    </script>
    </body>
    </html>

    index.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <style>
        </style>
    </head>
    <body>
        <ul>欢迎登录:{{ a }}</ul>
    </body>
    </html>

    验证

  • 相关阅读:
    hdu 4334 Trouble
    hdu 4324 Triangle LOVE
    hdu 4255 A Famous Grid
    hdu 3549 Flow Problem
    hdu 3371 Connect the Cities
    hdu 2846 Repository
    hdu 2120 Ice_cream's world I
    P3304 [SDOI2013]直径(【模板】树直径的必经边)
    P5490 【模板】扫描线
    P1364 医院设置(【模板】树的重心)
  • 原文地址:https://www.cnblogs.com/zhangzihong/p/8581071.html
Copyright © 2011-2022 走看看