九模板层

Posted dangjingwei

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了九模板层相关的知识,希望对你有一定的参考价值。

一、表单类1

#### 概述
表单既可以在模板页面利用html编写,也可以使用Django提供的表单类编写。
相关属性参考官网:https://docs.djangoproject.com/en/1.11/ref/forms/fields/

#### 实现熟悉的用户登录功能
1. 创建新应用account
2. settings中添加应用
3. 配置URL
4. 在account应用中创建forms.py文件
5. 编写views函数
6. 创建模板页面
7. 启动服务器运行程序
#### 配置URL
```
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
    url(r‘^admin/‘, admin.site.urls),
    url(r‘^account/‘,include(‘account.urls‘,namespace=‘account‘,app_name=‘account‘))
]

```
```
#coding=utf-8

from django.conf.urls import url
import views
urlpatterns=[
    url(r‘^login/$‘,views.login_view,name=‘login‘)
]
 
```

#### 编写表单类(account.forms.LoginForm)
```
#coding=utf-8

from django import forms
class LoginForm(forms.Form):
    username = forms.CharField(label=u‘用户名‘)
    password = forms.CharField(label=u‘密码‘,widget=forms.PasswordInput)
 
```
#### 配置视图函数
```
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.http import HttpResponse
from django.shortcuts import render
from .forms import LoginForm
from django.contrib.auth import authenticate,login
 
# Create your views here.
def login_view(request):
    if request.method==‘GET‘:
        login_form = LoginForm()
        return render(request,‘login.html‘,{‘login_form‘:login_form})
    else:
        login_form= LoginForm(request.POST)

        #校验表单数据是否合法
        if login_form.is_valid():
            #以字典形式返回合法数据
            cd = login_form.cleaned_data
            print cd
            #检验用户输入的用户和密码是否正确
            user = authenticate(username=cd[‘username‘],password=cd[‘password‘])
            print user
            if user:
                #实现用户登录,将用户信息保存到session中完成登录操作
                login(request,user)
                return HttpResponse(‘success‘)
        return HttpResponse(‘failed‘)
```
#### 配置模板页面(login.html)
```
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="" method="post">
        {% csrf_token %}
        {{ login_form.as_p }}
{#        {% for field in login_form %}#}
{#            {{ field.label_tag }}{{ field }}#}
{#            {{ field.errors }}#}
{#        {% endfor %}#}
        <input type="submit" value="登录"/>
    </form>
</body>
</html>
```
 
 二、表单类2
 
 
#### 应用场景
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>
‘‘‘‘‘‘‘

以上是关于九模板层的主要内容,如果未能解决你的问题,请参考以下文章

测开之路一百二十九:jinja2模板语法

订阅消息 | 小程序九九八十一坑之服务消息推送

Django-----视图层,模板层

HDOJ-1114(完全背包模板题)

Django之模板层

Django框架之模板层template的一些介绍和使用