循序渐进PYTHON3(十三) --0-- DJANGO之FORM表单
django为我们提供了form表单验证功能,下面来学习一下:
创建了django项目之后,创建app。
配置urls:
from django.conf.urls import url
from django.contrib import admin
from myapp01 import views
urlpatterns =[
url(r'^admin/', admin.site.urls),
url(r'^login/', views.login),
]
配置views(app01.views):
from django.shortcuts import render
from django import forms
# 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':
obj = InputForm(request.POST)
ret = obj.is_valid()
print(ret,obj.data)
if ret:
print(obj.clean())
else:
print(obj.errors)
return render(request, 'login.html')
配置tamplates(index.html):
<!DOCTYPE html>
<htmllang="en">
<head>
<metacharset="UTF-8">
<title>Title</title>
</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,
success:function(rdata){
console.log(rdata);
},
error:function(){
}
})
}
</script>
</body>
</html>
提交之后就可以获取输入的内容。