Django中ListView分页技术

分页技术在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#一个页面显示的条目

URL映射:

工程\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'),
)

工程\urls.py

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')),
)

模板文件:index.html


msg_board




Message:

{% if msg_list %} {%for msg in msg_list %} {% endfor%}
Title Content Author Ip Time Click
{{msg.title}} {{msg.content}} {{msg.user}} {{msg.ip}} {{msg.datetime}} {{msg.click_count}}
{% if is_paginated %} {%endif%} {% else %}

No msgs !!!

{% endif %}

效果图:

Django中ListView分页技术_第1张图片

你可能感兴趣的:(Python)