#### 应用场景
1. 查询时表单类只需要继承于forms.Form。
2. 增删改时表单类需要继承于forms.ModelForm。
#### 学生注册案例
#### 创建模型类
```
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
# Create your models here.
class Clazz(models.Model):
cno = models.AutoField(primary_key=True)
cname = models.CharField(max_length=20)
def __unicode__(self):
return u‘Clazz:%s‘%self.cname
class Stu(models.Model):
sno = models.AutoField(primary_key=True)
sname = models.CharField(max_length=30)
clazz = models.ForeignKey(Clazz,on_delete=models.CASCADE)
def __unicode__(self):
return u‘Stu:%s,%s‘%(self.sno,self.sname)
```
#### 创建表单类(应用包下创建forms.py)
```
#coding=utf-8
from django import forms
from .models import *
class Add_Clazz(forms.ModelForm):
class Meta:
model = Clazz
#元组形式
fields = (‘cname‘,)
class Add_Stu(forms.ModelForm):
class Meta:
model = Stu
fields = (‘sname‘,)
```
#### 配置URL
```
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r‘^admin/‘, admin.site.urls),
url(r‘^student/‘, include(‘student.urls‘)),
]
```
```
#coding=utf-8
from django.conf.urls import url
import views
urlpatterns=[
url(r‘^register/$‘,views.register)
]
```
#### 创建视图
```
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.http import HttpResponse
from django.shortcuts import render
from .forms import Add_Clazz,Add_Stu
# Create your views here.
def register(request):
if request.method==‘POST‘:
ac = Add_Clazz(request.POST)
astu = Add_Stu(request.POST)
if ac.is_valid()*astu.is_valid():
new_clazz = ac.save()
new_stu = astu.save(commit=False)
new_stu.clazz = new_clazz
new_stu.save()
return HttpResponse(‘successfully‘)
else:
return HttpResponse(‘sorry,you can not register.‘)
else:
ac = Add_Clazz()
astu = Add_Stu()
return render(request,‘register.html‘,{‘ac‘:ac,‘astu‘:astu})
```
#### 创建模板
```
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/student/register/" method="post">
{% csrf_token %}
<p>
<label for="{{ astu.sname.id_for_label }}">姓名:</label>{{ astu.sname }}
</p>
<p>
<label for="{{ ac.cname.id_for_label }}">班级:</label>{{ ac.cname }}
</p>
<p>
<input type="submit" value="注册" />
</p>
</form>
</body>
</html>
```
三、表单校验
1. JS前端校验
2. forms表单类自定义校验
#### 表单类
```
#coding=utf-8
from django import forms
from .models import *
class Add_Clazz(forms.ModelForm):
class Meta:
model = Clazz
fields = (‘cname‘,)
class Add_Stu(forms.ModelForm):
password = forms.CharField(max_length=30,widget=forms.PasswordInput)
password2 = forms.CharField(max_length=30,widget=forms.PasswordInput)
class Meta:
model = Stu
fields = (‘sname‘,)
def clean_password2(self):
cd = self.cleaned_data
if cd[‘password‘]!=cd[‘password2‘]:
self.errors[‘password2‘] = [‘密码不一致‘]
# raise forms.ValidationError(‘密码不一致!‘)
return cd[‘password2‘]
```
#### 视图函数
```
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.http import HttpResponse
from django.shortcuts import render
from .forms import Add_Clazz,Add_Stu
from . models import *
# Create your views here.
def register(request):
if request.method==‘POST‘:
ac = Add_Clazz(request.POST)
astu = Add_Stu(request.POST)
if ac.is_valid()*astu.is_valid():
try:
new_clazz = Clazz.objects.get(cname=ac.cleaned_data[‘cname‘])
except Clazz.DoesNotExist:
#保存数据到数据库
new_clazz = ac.save()
#保存数据对象不提交数据库
new_stu = astu.save(commit=False)
new_stu.clazz = new_clazz
new_stu.password = astu.clean_password2()
new_stu.save()
return HttpResponse(‘successfully‘)
else:
return render(request,‘register.html‘,{‘ac‘:ac,‘astu‘:astu})
else:
ac = Add_Clazz()
astu = Add_Stu()
return render(request,‘register.html‘,{‘ac‘:ac,‘astu‘:astu})
```
#### 模板页面
```
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/student/register/" method="post">
{% csrf_token %}
<p>
<label for="{{ astu.sname.id_for_label }}">姓名:</label>{{ astu.sname }}
</p>
<p>
<label for="{{ astu.password.id_for_label }}">密码:</label>{{ astu.password }}
</p>
<p>
<label for="{{ astu.password2.id_for_label }}">密码:</label>{{ astu.password2 }}<span style="color: red;">{{ astu.errors.password2.0 }}</span>
</p>
<p>
<label for="{{ ac.cname.id_for_label }}">班级:</label>{{ ac.cname }}
</p>
<p>
<input type="submit" value="注册" />
</p>
</form>
</body>
</html>
```
四、AJAX
#### 概要
Ajax 即“Asynchronous Javascript And XML”(异步 JavaScript 和 XML),是指一种创建交互式网页应用的网页开发技术。
局部刷新技术。
应用场景:
在页面比较复杂情况下,只需要更新局部内容。
#### 语法
1. GET请求
```
var data = {‘uname‘:‘zhangsan‘}
//发送ajax请求
$.get(‘/student/getinfo/‘,data,function(result){
alert(result.hello)
})
```
2. POST请求
```
var csrf = $(‘input[name="csrfmiddlewaretoken"]‘).val();
var data = {‘uname‘:‘zhangsan‘,‘csrfmiddlewaretoken‘:csrf}
$.post(‘/student/getinfo/‘,data,function(result){
alert(result.hello)
})
```
3. 自定义AJAX请求
```
$.ajax({
url:‘/student/getinfo/‘,
type:‘get‘,
data:‘uname=lisi&pwd=123‘,
async:true,
success:function (result) {
var test = result.hello
$(‘#hid‘).html(test)
}
})
```
五、Ajax用户名唯一校验
#### 确定需求
```
#访问路径:
http://127.0.0.1:8000/student/only/
```
#### 配置URL
```
# 项目包/urls.py
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r‘^admin/‘, admin.site.urls),
url(r‘^student/‘, include(‘stu.urls‘)),
]
# 应用包/urls.py
#coding=utf-8
from django.conf.urls import url
import views
urlpatterns=[
url(r‘^only/$‘,views.onlyView),
url(r‘^isExist/$‘,views.existView),
]
```
#### 创建视图
```
def onlyView(request):
return render(request,‘only.html‘)
def existView(request):
#接收请求参数
uname = request.GET.get(‘uname‘,‘‘)
#判断数据库中是否存在
stuList = Student.objects.filter(sname=uname)
if stuList:
return JsonResponse({‘flag‘:True})
return JsonResponse({‘flag‘:False})
```
#### 创建模板页面(only.html)
```
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/1.9.0/jquery.min.js"></script>
<script>
//onblur:失去焦点
//onfocus:获得焦点
function checkUname(){
//1.获取文本框内容
var uname = $(‘#uname‘).val();
//2.非空校验
if(uname.length==0){
$(‘#unameSpan‘).html(‘*‘);
$(‘#unameSpan‘).css(‘color‘,‘red‘);
}else{
//3.判断唯一性
$.get(‘/student/isExist/‘,{‘uname‘:uname},function(result){
//alert(typeof result.flag)
r = result.flag;
//4.根据服务器端的响应信息进行页面更新
if(r){
$(‘#unameSpan‘).html(‘此用户名太受欢迎了,请换一个吧~‘);
$(‘#unameSpan‘).css(‘color‘,‘red‘);
}else{
$(‘#unameSpan‘).html(‘√‘);
$(‘#unameSpan‘).css(‘color‘,‘green‘);
}
})
}
}
</script>
</head>
<body>
用户名:<input type="text" name="uname" id="uname" onblur="checkUname()"/><span id="unameSpan"></span>
</body>
</html>
```
六、Ajax三级联动菜单
#### 配置视图
```
from django.core import serializers
def showMenuInfo(request):
pid = request.GET.get(‘pid‘,-1)
pid = int(pid)
areaList = Area.objects.filter(parentid=pid)
jAreaList = serializers.serialize(‘json‘,areaList)
return JsonResponse({‘areaList‘:jAreaList})
```
#### 配置模板页面
```
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/1.9.0/jquery.min.js"></script>
<script>
$(function(){
showProvince();
});
function showProvince(){
showArea(‘province‘,0,showCity);
}
function showCity(){
showArea(‘city‘,$(‘#province‘).val(),showTown);
}
function showTown(){
showArea(‘town‘,$(‘#city‘).val());
}
function showArea(selectId,pid,nextLoad){
$(‘#‘+selectId).empty();
$.get(‘/stu/showMenu/‘,{‘pid‘:pid},function(result){
//将JSON字符串转成JSON对象
areaList = JSON.parse(result.areaList);
for(var i=0;i<areaList.length;i++){
var area = areaList[i];
$(‘#‘+selectId).append("<option value=‘"+area.pk+"‘>"+area.fields.areaname+"</option>")
}
if(nextLoad!=null){
nextLoad();
}
})
}
</script>
</head>
<body>
<select id="province" onchange="showCity();"></select>
<select id="city" onchange="showTown();"></select>
<select id="town"></select>
</body>
</html>
‘‘‘‘‘‘‘