在上一次的代码上做出进一步修改,使之能在页面上显示报错信息。
views.py
  1. from django.shortcuts import render,HttpResponse
  2. from django import forms
  3. import json
  4. # Create your views here.
  5. classInputForm(forms.Form):
  6. # 下面使用的变量名必须和html中input标签的name值相同
  7. username = forms.CharField(required=True)
  8. password = forms.CharField(required=True)
  9. def login(request):
  10. if request.method =='POST':
  11. result ={'status':False,'message':None}
  12. obj =InputForm(request.POST)
  13. ret = obj.is_valid()
  14. # print(ret,obj.data)
  15. if ret:
  16. print(obj.clean())
  17. result['status']=True
  18. else:
  19. # print(obj.errors)
  20. error_str = obj.errors.as_json()
  21. result['message']= json.loads(error_str)
  22. returnHttpResponse(json.dumps(result))
  23. return render(request,'login.html')
login.html
  1. <!DOCTYPE html>
  2. <htmllang="en">
  3. <head>
  4. <metacharset="UTF-8">
  5. <title>Title</title>
  6. <style>
  7. .error-msg{
  8. color:red;
  9. }
  10. </style>
  11. </head>
  12. <body>
  13. <div>
  14. <div>
  15. <inputtype="text"name="username"/>
  16. </div>
  17. <div>
  18. <inputtype="password"name="password"/>
  19. </div>
  20. <inputtype="button"value="提交"onclick="DoSubmit();"/>
  21. </div>
  22. <scriptsrc="/static/jquery-2.1.4.min.js"></script>
  23. <script>
  24. functionDoSubmit(){
  25. var input_dic ={};
  26. $('input').each(function(){
  27. var v = $(this).val();
  28. var n = $(this).attr('name');
  29. input_dic[n]= v;
  30. });
  31. console.log(input_dic);
  32. $.ajax({
  33. url:'/login/',
  34. type:'POST',
  35. data:input_dic,
  36. dataType:'json',
  37. success:function(rdata){
  38. if(rdata.status){
  39. location.href ='/index/';
  40. }else{
  41. $.each(rdata.message,function(k,v){
  42. console.log(k,v[0].message);
  43. var tag = document.createElement('span');
  44. tag.className ='error-msg';
  45. tag.innerText = v[0].message;
  46. $('input[name="'+ k +'"]').after(tag);
  47. })
  48. }
  49. },
  50. error:function(){
  51. }
  52. })
  53. }
  54. </script>
  55. </body>
  56. </html>
效果图: