分页技术在Web开发中应用非常频繁。常见的WEB中都是用javascript去控制的,而Django中分页非常方便,通过Pagination你可以很方便达到分页效果。今天主要说的是共同视图中ListView的分页处理,本质还是依赖与Pagination。
数据模型:models.py
from django.db import models from django.contrib.auth.models import User # Create your models here. class Msg(models.Model): title = models.CharField(max_length = 30) content = models.TextField() user = models.ForeignKey(User) ip = models.IPAddressField() datetime = models.DateTimeField(auto_now_add = True) click_count = models.IntegerField(default = 0) def __unicode__(self): return self.title
构造视图:views.py
from django.views.generic import ListView from msg_board.models import Msg ITEMS_PER_PAGE = 3 class MsgList(ListView): model = Msg#数据模型 context_object_name = 'msg_list'#模板中变量 template_name = 'index.html'#模板文件 paginate_by = ITEMS_PER_PAGE#一个页面显示的条目
工程\App\urls.py
from django.conf.urls import patterns, include, url from msg_board.views import MsgList urlpatterns = patterns('', # Examples: url(r'^$',MsgList.as_view(), name = 'index'), )
from django.conf.urls import patterns, include, url # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^$', 'mysite.views.home', name='home'), # url(r'^mysite/', include('mysite.mysite.urls')), # Uncomment the admin/doc line below to enable admin documentation: url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: url(r'^admin/', include(admin.site.urls)), #host page url(r'^mysite/',include('msg_board.urls', namespace = 'msg_board')), )
<html> <head><title>msg_board</title> <style type="text/css"> table{border:3 solid black; border-collapse:collapse} table th, table td{border:2 solid black} </style> </head> <body> <h3>Message:</h3> {% if msg_list %} <table id = "msgs"> <tr> <th>Title</th> <th>Content</th> <th>Author</th> <th>Ip</th> <th>Time</th> <th>Click</th> </tr> {%for msg in msg_list %} <tr> <td>{{msg.title}}</td> <td>{{msg.content}}</td> <td>{{msg.user}}</td> <td>{{msg.ip}}</td> <td>{{msg.datetime}}</td> <td>{{msg.click_count}}</td> </tr> {% endfor%} </table> {% if is_paginated %} <div class="pagination"> <span class="page-links"> {% if page_obj.has_previous %} <a href="/mysite?page={{ page_obj.previous_page_number }}">上一页</a> {% endif %} {% if page_obj.has_next %} <a href="/mysite?page={{ page_obj.next_page_number }}">下一页</a> {% endif %} <span class="page-current"> 第{{ page_obj.number }}页 ,工{{ page_obj.paginator.num_pages }}页。 </span> </span> </div> {%endif%} {% else %} <p>No msgs !!!</p> {% endif %} </body> </html>
效果图: