在上一次的代码上做出进一步修改,使之能在页面上显示报错信息。
views.py
from django.shortcuts import render, HttpResponse
from django import forms
import json
# Create your views here.
class InputForm(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)
return HttpResponse(json.dumps(result))
return render(request, 'login.html')
login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.error-msg{
color:red;
}
</style>
</head>
<body>
<div>
<div>
<input type="text" name="username" />
</div>
<div>
<input type="password" name="password" />
</div>
<input type="button" value="提交" onclick="DoSubmit();"/>
</div>
<script src="/static/jquery-2.1.4.min.js"></script>
<script>
function DoSubmit() {
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>
效果图: