循序渐进PYTHON3(十三) --1-- DJANGO之FORM表单
在上一次的代码上做出进一步修改,使之能在页面上显示报错信息。
views.py
from django.shortcuts import render,HttpResponse
from django import forms
import json
# Create your views here.
classInputForm(forms.Form):
# 下面使用的变量名必须和html中input标签的name值相同
username = forms.CharField(required=True)
password = forms.CharField(required=True)
def login(request):
if request.method =='POST':
result ={'status':False,'message':None}
obj =InputForm(request.POST)
ret = obj.is_valid()
# print(ret,obj.data)
if ret:
print(obj.clean())
result['status']=True
else:
# print(obj.errors)
error_str = obj.errors.as_json()
result['message']= json.loads(error_str)
returnHttpResponse(json.dumps(result))
return render(request,'login.html')
login.html
<!DOCTYPE html>
<htmllang="en">
<head>
<metacharset="UTF-8">
<title>Title</title>
<style>
.error-msg{
color:red;
}
</style>
</head>
<body>
<div>
<div>
<inputtype="text"name="username"/>
</div>
<div>
<inputtype="password"name="password"/>
</div>
<inputtype="button"value="提交"onclick="DoSubmit();"/>
</div>
<scriptsrc="/static/jquery-2.1.4.min.js"></script>
<script>
functionDoSubmit(){
var input_dic ={};
$('input').each(function(){
var v = $(this).val();
var n = $(this).attr('name');
input_dic[n]= v;
});
console.log(input_dic);
$.ajax({
url:'/login/',
type:'POST',
data:input_dic,
dataType:'json',
success:function(rdata){
if(rdata.status){
location.href ='/index/';
}else{
$.each(rdata.message,function(k,v){
console.log(k,v[0].message);
var tag = document.createElement('span');
tag.className ='error-msg';
tag.innerText = v[0].message;
$('input[name="'+ k +'"]').after(tag);
})
}
},
error:function(){
}
})
}
</script>
</body>
</html>
效果图: