分页技术在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')),
)
msg_board
Message:
{% if msg_list %}
Title
Content
Author
Ip
Time
Click
{%for msg in msg_list %}
{{msg.title}}
{{msg.content}}
{{msg.user}}
{{msg.ip}}
{{msg.datetime}}
{{msg.click_count}}
{% endfor%}
{% if is_paginated %}
{% if page_obj.has_previous %}
上一页
{% endif %}
{% if page_obj.has_next %}
下一页
{% endif %}
第{{ page_obj.number }}页 ,工{{ page_obj.paginator.num_pages }}页。
{%endif%}
{% else %}
No msgs !!!
{% endif %}
效果图: