(MacOSX10.7, Python2.7, Django1.3)
テスト用のプロジェクト作成や設定とか
django-admin.py startproject paginate cd paginate python manage.py startapp pagination cd pagination ls __init__.py models.py tests.py views.py
setting.py
import os BASE_DIR = os.path.dirname(os.path.abspath(__file__)) : DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'sqlite3.db', : } } : TEMPLATE_DIRS = ( os.path.join(BASE_DIR, 'templates'), ) : INSTALLED_APPS = ( : 'pagination', )
urls.py
from django.conf.urls.defaults import patterns, include, url urlpatterns = patterns('', url(r'^$', 'paginate.pagination.views.index'), )
models.py
from django.db import models class Entry(models.Model): title = models.CharField(max_length=200) def __unicode__(self): return self.title
views.py
from django.shortcuts import render_to_response from django.core.paginator import Paginator, InvalidPage, EmptyPage from paginate.pagination.models import Entry def index(request): entry = Entry.objects.all() paginator = Paginator(entry, 10) try: page = int(request.GET.get('page', '1')) except ValueError: page = 1 try: fp = paginator.page(page) except (EmptyPage, InvalidPage): fp = paginator.page(paginator.num_pages) return render_to_response('pagination/index.html', {'entry': fp})
index.html
ディレクトリを作成してindex.htmlファイルを作る
- /templates/pagination/index.html
{% for data in entry.object_list %} {{ data.title }} <br /> {% endfor %} <br /> <span> {% if entry.has_previous %} {% ifnotequal previous_page_number 1 %} <a href="?page=1">First</a> {% endifnotequal %} {% endif %} {% if entry.has_previous %} <a href="?page={{ entry.previous_page_number }}">Previous</a> {% endif %} {% for num in entry.paginator.page_range %} {% ifequal num entry.number %} <span class="current page">{{ num }}</span> {% else %} <a href="?page={{ num }}"> {{ num }}</a> {% endifequal %} {% endfor %} {% if entry.has_next %} <a href="?page={{ entry.next_page_number }}"> Next </a> {% endif %} {% if entry.has_next %} {% ifnotequal next_page_number entry.paginator.num_pages %} <a href="?page={{ entry.paginator.num_pages }}">Last</a> {% endifnotequal %} {% endif %} </span>
動作確認
syncdb
python manage.py syncdb
テストデータ作成
python manage.py shell >>> from paginate.pagination.models import Entry >>> Entry.objects.all() #-> [] >>> for i in range(100): ... Entry(title="title:{0:08d}".format(i)).save() >>> Entry.objects.all() #-> [<Entry: titel00000000>, <Entry: titel00000001>, ...
runserver
python manage.py runserver
webブラウザで確認
参考サイト
メモ
- プロジェクト名、アプリ名をもっと分かりやすいものでやればよかった(´・ω・`)