Django 分页和使用Ajax5.3
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                Django 分页和使用Ajax5.3
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.                        
                                分頁
- Django提供了一些類實現管理數據分頁,這些類位于django/core/paginator.py中
Paginator對象
- Paginator(列表,int):返回分頁對象,參數為列表數據,每面數據的條數
屬性
- count:對象總數
- num_pages:頁面總數
- page_range:頁碼列表,從1開始,例如[1, 2, 3, 4]
方法
- page(num):下標以1開始,如果提供的頁碼不存在,拋出InvalidPage異常
異常exception
- InvalidPage:當向page()傳入一個無效的頁碼時拋出
- PageNotAnInteger:當向page()傳入一個不是整數的值時拋出
- EmptyPage:當向page()提供一個有效值,但是那個頁面上沒有任何對象時拋出
Page對象
創建對象
- Paginator對象的page()方法返回Page對象,不需要手動構造
屬性
- object_list:當前頁上所有對象的列表
- number:當前頁的序號,從1開始
- paginator:當前page對象相關的Paginator對象
方法
- has_next():如果有下一頁返回True
- has_previous():如果有上一頁返回True
- has_other_pages():如果有上一頁或下一頁返回True
- next_page_number():返回下一頁的頁碼,如果下一頁不存在,拋出InvalidPage異常
- previous_page_number():返回上一頁的頁碼,如果上一頁不存在,拋出InvalidPage異常
- len():返回當前頁面對象的個數
- 迭代頁面對象:訪問當前頁面中的每個對象
示例
創建視圖pagTest
from django.core.paginator import Paginatordef pagTest(request, pIndex):list1 = AreaInfo.objects.filter(aParent__isnull=True)p = Paginator(list1, 10)if pIndex == '':pIndex = '1'pIndex = int(pIndex)list2 = p.page(pIndex)plist = p.page_rangereturn render(request, 'booktest/pagTest.html', {'list': list2, 'plist': plist, 'pIndex': pIndex})
配置url
url(r'^pag(?P<pIndex>[0-9]*)/$', views.pagTest, name='pagTest'),
定義模板pagTest.html
<!DOCTYPE html>
<html>
<head><title></title>
</head>
<body>
<ul>
{%for area in list%}
<li>{{area.id}}--{{area.atitle}}</li>
{%endfor%}
</ul>{%for pindex in plist%}
{%if pIndex == pindex%}
{{pindex}}  
{%else%}
<a href="/pag{{pindex}}/">{{pindex}}</a>  
{%endif%}
{%endfor%}
</body>
</html>使用Ajax
- 使用視圖通過上下文向模板中傳遞數據,需要先加載完成模板的靜態頁面,再執行模型代碼,生成最張的html,返回給瀏覽器,這個過程將頁面與數據集成到了一起,擴展性差
- 改進方案:通過ajax的方式獲取數據,通過dom操作將數據呈現到界面上
- 推薦使用框架的ajax相關方法,不要使用XMLHttpRequest對象,因為操作麻煩且不容易查錯
- jquery框架中提供了$.ajax、$.get、$.post方法,用于進行異步交互
- 由于csrf的約束,推薦使用$.get
- 示例:實現省市區的選擇
- 最終實現效果如圖:
引入js文件
- js文件屬于靜態文件,創建目錄結構如圖:
修改settings.py關于靜態文件的設置
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'),
]
在models.py中定義模型
class AreaInfo(models.Model):aid = models.IntegerField(primary_key=True)atitle = models.CharField(max_length=20)aPArea = models.ForeignKey('AreaInfo', null=True)
生成遷移
python manage.py makemigrations
python manage.py migrate
通過workbench向表中填充示例數據
- 參見“省市區.sql”
- 注意將表的名稱完成替換
在views.py中編寫視圖
- index用于展示頁面
- getArea1用于返回省級數據
- getArea2用于根據省、市編號返回市、區信息,格式都為字典對象
from django.shortcuts import render
from django.http import JsonResponse
from models import AreaInfodef index(request):return render(request, 'ct1/index.html')def getArea1(request):list = AreaInfo.objects.filter(aPArea__isnull=True)list2 = []for a in list:list2.append([a.aid, a.atitle])return JsonResponse({'data': list2})def getArea2(request, pid):list = AreaInfo.objects.filter(aPArea_id=pid)list2 = []for a in list:list2.append({'id': a.aid, 'title': a.atitle})return JsonResponse({'data': list2})
在urls.py中配置urlconf
from django.conf.urls import url
from . import viewsurlpatterns = [url(r'^$', views.index),url(r'^area1/$', views.getArea1),url(r'^([0-9]+)/$', views.getArea2),
]
主urls.py中包含此應用的url
from django.conf.urls import include, url
from django.contrib import adminurlpatterns = [url(r'^', include('ct1.urls', namespace='ct1')),url(r'^admin/', include(admin.site.urls)),
]
定義模板index.html
- 在項目中的目錄結構如圖:
- 修改settings.py的TEMPLATES項,設置DIRS值
'DIRS': [os.path.join(BASE_DIR, 'templates')],
- 定義模板文件:包含三個select標簽,分別存放省市區的信息
<!DOCTYPE html>
<html>
<head><title>省市區列表</title>
</head>
<body>
<select id="pro"><option value="">請選擇省</option>
</select>
<select id="city"><option value="">請選擇市</option>
</select>
<select id="dis"><option value="">請選擇區縣</option>
</select>
</body>
</html>
在模板中引入jquery文件
<script type="text/javascript" src="static/ct1/js/jquery-1.12.4.min.js"></script>
編寫js代碼
- 綁定change事件
- 發出異步請求
- 使用dom添加元素
    <script type="text/javascript">$(function(){$.get('area1/',function(dic) {pro=$('#pro')$.each(dic.data,function(index,item){pro.append('<option value='+item[0]+'>'+item[1]+'</option>');})});$('#pro').change(function(){$.post($(this).val()+'/',function(dic){city=$('#city');city.empty().append('<option value="">請選擇市</option>');$.each(dic.data,function(index,item){city.append('<option value='+item.id+'>'+item.title+'</option>');})});});$('#city').change(function(){$.post($(this).val()+'/',function(dic){dis=$('#dis');dis.empty().append('<option value="">請選擇區縣</option>');$.each(dic.data,function(index,item){dis.append('<option value='+item.id+'>'+item.title+'</option>');})})});});</script>?
總結
以上是生活随笔為你收集整理的Django 分页和使用Ajax5.3的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: Django 上传图片和Admin站点5
- 下一篇: Django 第三方引用富文本编辑器6.
