1、打开命令行窗口,创建Django工程,使用以下命令:django-admin startproject djpagecd djpagepython manage.py startapp demo
2、使用PyCharm打开工程,在工程的同名文件夹的settings.py文件,注册应用,添加模板路悄钸碌灵径,修改部分的settings.py内容如下:INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'demo.apps.DemoConfig']TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, },]
3、在工程同名文件的urls.py文件,添加到应用的视图的路由from django.conf.urls import urlfrom django.contrib import adminfrom demo import viewsurlpatterns = [ url(r'^admin/', admin.site.urls), url(r'page/(?P<id>\d+)/$',views.page)]
4、在应用的视图views.py文件,编写处理请求函数,实现分页显示一个列表的内容,这里列表也可以是查询集from django.shortcuts import renderfrom django.core.paginator import Paginator# Create your views here.def page(request,id): hello_list = [{'title':'hello'},{'title':'world'}, {'title':'hello1'},{'title':'world1'}, {'title':'hello2'},{'title':'world2'}, {'title':'hello3'},{'title':'world3'}, {'title':'hello4'},{'title':'world4'}] pag = Paginator(hello_list, 2) page = pag.page(int(id)) return render(request,template_name='home.html', context={'page': page})
5、在工程根目录新建templates文件夹,并创建一个home.html文件,代码如下:<!DOCTYPE html媪青怍牙><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title></head><body> <ul> {% for item in page %} <li>{{item.title}}</li> {% endfor %} </ul> {% if page.has_previous %} <a href="/page/{{ page.previous_page_number }}"><上一页</a> {% endif %} {# 遍历显示页码的链接 #} {% for index in page.paginator.page_range %} {# 判断是否是当前页 #} {% if index == page.number %} {{ index }} {% else %} <a href="/page/{{ index }}">{{ index }}</a> {% endif %} {% endfor %} {# 判断是否有下一页 #} {% if page.has_next %} <a href="/page/{{ page.next_page_number }}">下一页></a> {% endif %}</body></html><!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title></head><body> <ul> {% for item in page %} <li>{{item.title}}</li> {% endfor %} </ul> {% if page.has_previous %} <a href="/page/{{ page.previous_page_number }}"><上一页</a> {% endif %} {# 遍历显示页码的链接 #} {% for index in page.paginator.page_range %} {# 判断是否是当前页 #} {% if index == page.number %} {{ index }} {% else %} <a href="/page/{{ index }}">{{ index }}</a> {% endif %} {% endfor %} {# 判断是否有下一页 #} {% if page.has_next %} <a href="/page/{{ page.next_page_number }}">下一页></a> {% endif %}</body></html>page.paginator.page_range是页面总数
6、运行django服务器python manage.py runserver
7、打开网页,输入http://127.0.0.1:8000/page/1显示效果图如下,分页成功