一、
在users/views.py中加代码:
from django.http import HttpResponse class LoginView(View): """用户登录""" def get(self,request): return render(request,'index.html',{}) def post(self,request): user_name=request.POST.get("username","") pass_word=request.POST.get("password","") user=authenticate(username=user_name,password=pass_word) if user is not None: login(request,user) return HttpResponse('{"status":"success"}') else: return HttpResponse('{"status":"fail"},{"msg":"用户名或密码错误"}')
这里注意,HttpResponse(字符串) 如果是像字典的字符串,只可以是单引号包双引号,而不能相反,不然回调到前端时,JSON.parse(字符串)就会报错!
二、
在users/urls.py中配置路由
...... from .views import LoginView ...... urlpatterns = [ ...... path('login/',LoginView.as_view(),name='login'), ...... ]
三、
在前端的base.html中
在登录对应的模态框代码中:
<!-- Modal --> <div class="modal fade" id="login" tabindex="-1" role="dialog"> <div class="modal-dialog" role="document"> <div class="modal-content" style=" 500px"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button> <h4 class="modal-title" style="text-align: center">用户登录</h4> </div> <!--关键代码start--> <div class="modal-body"> <form id="loginform" action="#" method="post"> <p><div style="display: inline-block;150px;text-align: center"> <b>用户名或邮箱:</b> </div> <input type="text" name="username" placeholder="用户名/邮箱"></p> <p><div style="display: inline-block;150px;text-align: center"> <b >密码:</b> </div> <input type="password" name="pwd" placeholder="密码"></p> {% csrf_token %} </form> <p><div style="margin-right: auto;margin-left: auto;background-color: orangered;150px;text-align: center"> <b id="login-fail"></b> </div></p> </div> <!--关键代码end--> <div class="modal-footer"> <button type="button" class="btn btn-default">忘记密码</button> <!--关键代码start--> <button type="button" class="btn btn-primary" id="loginbtn">确认登录</button> <!--关键代码end--> </div> </div><!-- /.modal-content --> </div><!-- /.modal-dialog --> </div><!-- /.modal -->
写ajax提交代码:
<script> $("#loginbtn").click(function() { $.ajax({ cache:false, type:"POST", url:"{% url 'users:login' %}", dataType:'json', data:$('#loginform').serialize(), //通过id找到提交form表单,并将表单转成字符串 async:true, //异步为真,ajax提交的过程中,同时可以做其他的操作 success:function (data) { //jquery3以后,会将回传过来的字符串格式的data自动json解析不用再使用一遍JSON.parse(data)了,不然反而会在控制台报错 if(data.status=="success"){ location.reload(); }else if(data.status=="fail"){ $('#login-fail').html(data.msg); } } }); }) //如果显示了错误信息,修改输入框内容,错误信息隐藏 $("input").bind('input propertychange', function() { $('#login-fail').html(''); }); </script>