├── .gitignore ├── .travis.yml ├── LICENSE ├── MANIFEST.in ├── README.rst ├── docs ├── Makefile ├── conf.py ├── contributing.rst ├── index.rst ├── settings.rst ├── simple_pagination.rst ├── start.rst └── templatetags_reference.rst ├── sandbox ├── manage.py ├── requirements.txt ├── sample │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── migrations │ │ └── __init__.py │ ├── models.py │ ├── tests.py │ └── views.py ├── simple_pagination │ ├── __init__.py │ ├── admin.py │ ├── migrations │ │ └── __init__.py │ ├── models.py │ ├── settings.py │ ├── templates │ │ └── simple │ │ │ ├── current_link.html │ │ │ ├── page_link.html │ │ │ └── show_pages.html │ ├── templatetags │ │ ├── __init__.py │ │ └── paginate.py │ ├── tests.py │ └── utils.py ├── templates │ └── users.html └── test_pagination │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── setup.py ├── simple_pagination ├── __init__.py ├── admin.py ├── migrations │ └── __init__.py ├── models.py ├── settings.py ├── templates │ └── simple │ │ ├── current_link.html │ │ ├── page_link.html │ │ └── show_pages.html ├── templatetags │ ├── __init__.py │ └── paginate.py ├── tests.py └── utils.py └── test_runner.py /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | *~ 3 | db.sqlite3 4 | django_simple_pagination 5 | dist 6 | build 7 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | 3 | python: 4 | - "3.5" 5 | - "3.6" 6 | - "3.7" 7 | 8 | install: 9 | - python setup.py install 10 | - pip install coveralls 11 | 12 | script: 13 | - coverage run --source=simple_pagination test_runner.py test 14 | 15 | after_success: 16 | coveralls 17 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2020 MicroPyramid 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | 23 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include README.rst 2 | recursive-include simple_pagination/templates * -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | .. image:: https://travis-ci.org/MicroPyramid/django-simple-pagination.svg?branch=master 2 | :target: https://travis-ci.org/MicroPyramid/django-simple-pagination 3 | 4 | .. image:: https://img.shields.io/pypi/v/django-simple-pagination.svg 5 | :target: https://pypi.python.org/pypi/django-simple-pagination 6 | :alt: Latest Release 7 | 8 | .. image:: https://coveralls.io/repos/github/MicroPyramid/django-simple-pagination/badge.svg?branch=master 9 | :target: https://coveralls.io/github/MicroPyramid/django-simple-pagination?branch=master 10 | 11 | .. image:: https://landscape.io/github/MicroPyramid/django-simple-pagination/master/landscape.svg?style=flat 12 | :target: https://landscape.io/github/MicroPyramid/django-simple-pagination/master 13 | :alt: Code Health 14 | 15 | .. image:: https://img.shields.io/github/license/micropyramid/django-simple-pagination.svg 16 | :target: https://pypi.python.org/pypi/django-simple-pagination/ 17 | 18 | `Django Simple Pagination`_ is a simple Django app to for digg-style pagination with little effort. 19 | 20 | **Documentation** is `avaliable online`_, or in the docs 21 | directory of the project. 22 | 23 | Quick start 24 | ----------- 25 | 26 | 1. Install 'Django-Simple-Pagination' using the following command:: 27 | 28 | pip install django-simple-pagination 29 | 30 | 2. Add ``simple_pagination`` to your INSTALLED_APPS setting like this:: 31 | 32 | INSTALLED_APPS = [ 33 | ... 34 | 'simple_pagination', 35 | ] 36 | 3. In templates use ``{% load paginate %}`` to load all pagination template tags 37 | 4. In templates use ``{% paginate no_of_records entities %}`` to get pagination objects. 38 | 39 | Here no_of_records means no of objects to display in a page and entities means the list of objects 40 | 41 | 42 | 5. In templates use ``{% show_pageitems %}`` to get digg-style page links. 43 | 44 | Questions, Comments, etc? 45 | ------------------------- 46 | 47 | We welcome your feedback and support, raise `github ticket`_ if you want to report a bug. Need new features? `Contact us here`_ 48 | 49 | Visit our Django web development page `Here`_ 50 | 51 | .. _contact us here: https://micropyramid.com/contact-us/ 52 | .. _avaliable online: http://django-simple-pagination.readthedocs.org/ 53 | .. _github ticket: https://github.com/MicroPyramid/django-simple-pagination/issues 54 | .. _Django Simple Pagination: https://micropyramid.com/oss/ 55 | .. _Here: https://micropyramid.com/django-development-services/ 56 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = build 9 | 10 | # User-friendly check for sphinx-build 11 | ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) 12 | $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) 13 | endif 14 | 15 | # Internal variables. 16 | PAPEROPT_a4 = -D latex_paper_size=a4 17 | PAPEROPT_letter = -D latex_paper_size=letter 18 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 19 | # the i18n builder cannot share the environment and doctrees with the others 20 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 21 | 22 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest coverage gettext 23 | 24 | help: 25 | @echo "Please use \`make ' where is one of" 26 | @echo " html to make standalone HTML files" 27 | @echo " dirhtml to make HTML files named index.html in directories" 28 | @echo " singlehtml to make a single large HTML file" 29 | @echo " pickle to make pickle files" 30 | @echo " json to make JSON files" 31 | @echo " htmlhelp to make HTML files and a HTML help project" 32 | @echo " qthelp to make HTML files and a qthelp project" 33 | @echo " applehelp to make an Apple Help Book" 34 | @echo " devhelp to make HTML files and a Devhelp project" 35 | @echo " epub to make an epub" 36 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 37 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 38 | @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" 39 | @echo " text to make text files" 40 | @echo " man to make manual pages" 41 | @echo " texinfo to make Texinfo files" 42 | @echo " info to make Texinfo files and run them through makeinfo" 43 | @echo " gettext to make PO message catalogs" 44 | @echo " changes to make an overview of all changed/added/deprecated items" 45 | @echo " xml to make Docutils-native XML files" 46 | @echo " pseudoxml to make pseudoxml-XML files for display purposes" 47 | @echo " linkcheck to check all external links for integrity" 48 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 49 | @echo " coverage to run coverage check of the documentation (if enabled)" 50 | 51 | clean: 52 | rm -rf $(BUILDDIR)/* 53 | 54 | html: 55 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 56 | @echo 57 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 58 | 59 | dirhtml: 60 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 61 | @echo 62 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 63 | 64 | singlehtml: 65 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 66 | @echo 67 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 68 | 69 | pickle: 70 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 71 | @echo 72 | @echo "Build finished; now you can process the pickle files." 73 | 74 | json: 75 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 76 | @echo 77 | @echo "Build finished; now you can process the JSON files." 78 | 79 | htmlhelp: 80 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 81 | @echo 82 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 83 | ".hhp project file in $(BUILDDIR)/htmlhelp." 84 | 85 | qthelp: 86 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 87 | @echo 88 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 89 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 90 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/a.qhcp" 91 | @echo "To view the help file:" 92 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/a.qhc" 93 | 94 | applehelp: 95 | $(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp 96 | @echo 97 | @echo "Build finished. The help book is in $(BUILDDIR)/applehelp." 98 | @echo "N.B. You won't be able to view it unless you put it in" \ 99 | "~/Library/Documentation/Help or install it in your application" \ 100 | "bundle." 101 | 102 | devhelp: 103 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 104 | @echo 105 | @echo "Build finished." 106 | @echo "To view the help file:" 107 | @echo "# mkdir -p $$HOME/.local/share/devhelp/a" 108 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/a" 109 | @echo "# devhelp" 110 | 111 | epub: 112 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 113 | @echo 114 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 115 | 116 | latex: 117 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 118 | @echo 119 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 120 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 121 | "(use \`make latexpdf' here to do that automatically)." 122 | 123 | latexpdf: 124 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 125 | @echo "Running LaTeX files through pdflatex..." 126 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 127 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 128 | 129 | latexpdfja: 130 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 131 | @echo "Running LaTeX files through platex and dvipdfmx..." 132 | $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja 133 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 134 | 135 | text: 136 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 137 | @echo 138 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 139 | 140 | man: 141 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 142 | @echo 143 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 144 | 145 | texinfo: 146 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 147 | @echo 148 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 149 | @echo "Run \`make' in that directory to run these through makeinfo" \ 150 | "(use \`make info' here to do that automatically)." 151 | 152 | info: 153 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 154 | @echo "Running Texinfo files through makeinfo..." 155 | make -C $(BUILDDIR)/texinfo info 156 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 157 | 158 | gettext: 159 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 160 | @echo 161 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 162 | 163 | changes: 164 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 165 | @echo 166 | @echo "The overview file is in $(BUILDDIR)/changes." 167 | 168 | linkcheck: 169 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 170 | @echo 171 | @echo "Link check complete; look for any errors in the above output " \ 172 | "or in $(BUILDDIR)/linkcheck/output.txt." 173 | 174 | doctest: 175 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 176 | @echo "Testing of doctests in the sources finished, look at the " \ 177 | "results in $(BUILDDIR)/doctest/output.txt." 178 | 179 | coverage: 180 | $(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage 181 | @echo "Testing of coverage in the sources finished, look at the " \ 182 | "results in $(BUILDDIR)/coverage/python.txt." 183 | 184 | xml: 185 | $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml 186 | @echo 187 | @echo "Build finished. The XML files are in $(BUILDDIR)/xml." 188 | 189 | pseudoxml: 190 | $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml 191 | @echo 192 | @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." 193 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # pietrack documentation build configuration file, created by 4 | # sphinx-quickstart on Wed Jul 29 18:10:32 2015. 5 | # 6 | # This file is execfile()d with the current directory set to its 7 | # containing dir. 8 | # 9 | # Note that not all possible configuration values are present in this 10 | # autogenerated file. 11 | # 12 | # All configuration values have a default; values that are commented out 13 | # serve to show the default. 14 | 15 | import sphinx_rtd_theme 16 | import sys 17 | import os 18 | import shlex 19 | 20 | # If extensions (or modules to document with autodoc) are in another directory, 21 | # add these directories to sys.path here. If the directory is relative to the 22 | # documentation root, use os.path.abspath to make it absolute, like shown here. 23 | # sys.path.insert(0, os.path.abspath('.')) 24 | 25 | # -- General configuration ------------------------------------------------ 26 | 27 | # If your documentation needs a minimal Sphinx version, state it here. 28 | # needs_sphinx = '1.0' 29 | 30 | # Add any Sphinx extension module names here, as strings. They can be 31 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 32 | # ones. 33 | extensions = [ 34 | 'sphinx.ext.autodoc', 35 | ] 36 | 37 | # Add any paths that contain templates here, relative to this directory. 38 | templates_path = ['_templates'] 39 | 40 | # The suffix(es) of source filenames. 41 | # You can specify multiple suffix as a list of string: 42 | # source_suffix = ['.rst', '.md'] 43 | source_suffix = '.rst' 44 | 45 | # The encoding of source files. 46 | # source_encoding = 'utf-8-sig' 47 | 48 | # The master toctree document. 49 | master_doc = 'index' 50 | 51 | # General information about the project. 52 | project = u'django-simple-pagination' 53 | copyright = u'2020, MicroPyramid' 54 | author = u'MicroPyramid' 55 | 56 | # The version info for the project you're documenting, acts as replacement for 57 | # |version| and |release|, also used in various other places throughout the 58 | # built documents. 59 | # 60 | # The short X.Y version. 61 | version = '1.4' 62 | # The full version, including alpha/beta/rc tags. 63 | release = '1.4' 64 | 65 | # The language for content autogenerated by Sphinx. Refer to documentation 66 | # for a list of supported languages. 67 | # 68 | # This is also used if you do content translation via gettext catalogs. 69 | # Usually you set "language" from the command line for these cases. 70 | language = None 71 | 72 | # There are two options for replacing |today|: either, you set today to some 73 | # non-false value, then it is used: 74 | # today = '' 75 | # Else, today_fmt is used as the format for a strftime call. 76 | # today_fmt = '%B %d, %Y' 77 | 78 | # List of patterns, relative to source directory, that match files and 79 | # directories to ignore when looking for source files. 80 | exclude_patterns = [] 81 | 82 | # The reST default role (used for this markup: `text`) to use for all 83 | # documents. 84 | # default_role = None 85 | 86 | # If true, '()' will be appended to :func: etc. cross-reference text. 87 | # add_function_parentheses = True 88 | 89 | # If true, the current module name will be prepended to all description 90 | # unit titles (such as .. function::). 91 | # add_module_names = True 92 | 93 | # If true, sectionauthor and moduleauthor directives will be shown in the 94 | # output. They are ignored by default. 95 | # show_authors = False 96 | 97 | # The name of the Pygments (syntax highlighting) style to use. 98 | pygments_style = 'sphinx' 99 | 100 | # A list of ignored prefixes for module index sorting. 101 | # modindex_common_prefix = [] 102 | 103 | # If true, keep warnings as "system message" paragraphs in the built documents. 104 | # keep_warnings = False 105 | 106 | # If true, `todo` and `todoList` produce output, else they produce nothing. 107 | todo_include_todos = False 108 | 109 | 110 | # -- Options for HTML output ---------------------------------------------- 111 | 112 | # The theme to use for HTML and HTML Help pages. See the documentation for 113 | # a list of builtin themes. 114 | 115 | html_theme = "sphinx_rtd_theme" 116 | 117 | html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] 118 | 119 | # Theme options are theme-specific and customize the look and feel of a theme 120 | # further. For a list of options available for each theme, see the 121 | # documentation. 122 | # html_theme_options = {} 123 | 124 | # Add any paths that contain custom themes here, relative to this directory. 125 | # html_theme_path = [] 126 | 127 | # The name for this set of Sphinx documents. If None, it defaults to 128 | # " v documentation". 129 | # html_title = None 130 | 131 | # A shorter title for the navigation bar. Default is the same as html_title. 132 | # html_short_title = None 133 | 134 | # The name of an image file (relative to this directory) to place at the top 135 | # of the sidebar. 136 | # html_logo = None 137 | 138 | # The name of an image file (within the static path) to use as favicon of the 139 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 140 | # pixels large. 141 | # html_favicon = None 142 | 143 | # Add any paths that contain custom static files (such as style sheets) here, 144 | # relative to this directory. They are copied after the builtin static files, 145 | # so a file named "default.css" will overwrite the builtin "default.css". 146 | html_static_path = ['_static'] 147 | 148 | # Add any extra paths that contain custom files (such as robots.txt or 149 | # .htaccess) here, relative to this directory. These files are copied 150 | # directly to the root of the documentation. 151 | # html_extra_path = [] 152 | 153 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, 154 | # using the given strftime format. 155 | # html_last_updated_fmt = '%b %d, %Y' 156 | 157 | # If true, SmartyPants will be used to convert quotes and dashes to 158 | # typographically correct entities. 159 | # html_use_smartypants = True 160 | 161 | # Custom sidebar templates, maps document names to template names. 162 | # html_sidebars = {} 163 | 164 | # Additional templates that should be rendered to pages, maps page names to 165 | # template names. 166 | # html_additional_pages = {} 167 | 168 | # If false, no module index is generated. 169 | # html_domain_indices = True 170 | 171 | # If false, no index is generated. 172 | # html_use_index = True 173 | 174 | # If true, the index is split into individual pages for each letter. 175 | # html_split_index = False 176 | 177 | # If true, links to the reST sources are added to the pages. 178 | # html_show_sourcelink = True 179 | 180 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 181 | # html_show_sphinx = True 182 | 183 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 184 | # html_show_copyright = True 185 | 186 | # If true, an OpenSearch description file will be output, and all pages will 187 | # contain a tag referring to it. The value of this option must be the 188 | # base URL from which the finished HTML is served. 189 | # html_use_opensearch = '' 190 | 191 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 192 | # html_file_suffix = None 193 | 194 | # Language to be used for generating the HTML full-text search index. 195 | # Sphinx supports the following languages: 196 | # 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' 197 | # 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' 198 | # html_search_language = 'en' 199 | 200 | # A dictionary with options for the search language support, empty by default. 201 | # Now only 'ja' uses this config value 202 | # html_search_options = {'type': 'default'} 203 | 204 | # The name of a javascript file (relative to the configuration directory) that 205 | # implements a search results scorer. If empty, the default will be used. 206 | # html_search_scorer = 'scorer.js' 207 | 208 | # Output file base name for HTML help builder. 209 | htmlhelp_basename = 'simplepagination' 210 | 211 | # -- Options for LaTeX output --------------------------------------------- 212 | 213 | latex_elements = { 214 | # The paper size ('letterpaper' or 'a4paper'). 215 | # 'papersize': 'letterpaper', 216 | 217 | # The font size ('10pt', '11pt' or '12pt'). 218 | # 'pointsize': '10pt', 219 | 220 | # Additional stuff for the LaTeX preamble. 221 | # 'preamble': '', 222 | 223 | # Latex figure (float) alignment 224 | # 'figure_align': 'htbp', 225 | } 226 | 227 | # Grouping the document tree into LaTeX files. List of tuples 228 | # (source start file, target name, title, 229 | # author, documentclass [howto, manual, or own class]). 230 | latex_documents = [ 231 | (master_doc, 'simplepagination.tex', u'django simple pagination Documentation', 232 | u'MicroPyramid', 'manual'), 233 | ] 234 | 235 | # The name of an image file (relative to this directory) to place at the top of 236 | # the title page. 237 | # latex_logo = None 238 | 239 | # For "manual" documents, if this is true, then toplevel headings are parts, 240 | # not chapters. 241 | # latex_use_parts = False 242 | 243 | # If true, show page references after internal links. 244 | # latex_show_pagerefs = False 245 | 246 | # If true, show URL addresses after external links. 247 | # latex_show_urls = False 248 | 249 | # Documents to append as an appendix to all manuals. 250 | # latex_appendices = [] 251 | 252 | # If false, no module index is generated. 253 | # latex_domain_indices = True 254 | 255 | 256 | # -- Options for manual page output --------------------------------------- 257 | 258 | # One entry per manual page. List of tuples 259 | # (source start file, name, description, authors, manual section). 260 | man_pages = [ 261 | (master_doc, 'simplepagination', u'django simple pagination Documentation', 262 | [author], 1) 263 | ] 264 | 265 | # If true, show URL addresses after external links. 266 | # man_show_urls = False 267 | 268 | 269 | # -- Options for Texinfo output ------------------------------------------- 270 | 271 | # Grouping the document tree into Texinfo files. List of tuples 272 | # (source start file, target name, title, author, 273 | # dir menu entry, description, category) 274 | texinfo_documents = [ 275 | (master_doc, 'simplepagination', u'django simple pagination Documentation', 276 | author, 'simplepagination', 'One line description of project.', 277 | 'Miscellaneous'), 278 | ] 279 | 280 | # Documents to append as an appendix to all manuals. 281 | # texinfo_appendices = [] 282 | 283 | # If false, no module index is generated. 284 | # texinfo_domain_indices = True 285 | 286 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 287 | # texinfo_show_urls = 'footnote' 288 | 289 | # If true, do not generate a @detailmenu in the "Top" node's menu. 290 | # texinfo_no_detailmenu = False 291 | -------------------------------------------------------------------------------- /docs/contributing.rst: -------------------------------------------------------------------------------- 1 | ************ 2 | Contributing 3 | ************ 4 | 5 | Feel free to create a new Pull request if you want to propose a new feature 6 | or fix a bug. 7 | 8 | Sending pull requests 9 | ===================== 10 | 11 | 1. Fork the repo:: 12 | 13 | https://github.com/MicroPyramid/django-simple-pagination.git 14 | 15 | 2. Create a branch for your specific changes:: 16 | 17 | $ git checkout master 18 | $ git pull 19 | $ git checkout -b feature 20 | 21 | To simplify things, please, make one branch per issue (pull request). 22 | It's also important to make sure your branch is up-to-date with upstream master, 23 | so that maintainers can merge changes easily. 24 | 25 | 3. Commit changes. Please update docs, if relevant. 26 | 27 | 4. Don't forget to run tests to check than nothing breaks. 28 | 29 | 5. Ideally, write your own tests for new feature/bug fix. 30 | 31 | 6. Submit a `pull request`_. 32 | 33 | .. _pull request: https://help.github.com/articles/using-pull-requests -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | ========================= 2 | Django Simple Pagination 3 | ========================= 4 | 5 | This application provides simple Digg-style pagination. It is devoted to implementing 6 | web pagination in very few steps. 7 | 8 | The **source code** for this app is hosted at 9 | https://github.com/MicroPyramid/django-simple-pagination.git 10 | 11 | :doc:`start` is easy! 12 | 13 | Contents: 14 | 15 | .. toctree:: 16 | :maxdepth: 2 17 | 18 | start 19 | simple_pagination 20 | templatetags_reference 21 | settings 22 | contributing -------------------------------------------------------------------------------- /docs/settings.rst: -------------------------------------------------------------------------------- 1 | ******** 2 | Settings 3 | ******** 4 | 5 | .. highlight:: python 6 | 7 | ``SIMPLE_PAGINATION_PER_PAGE`` 8 | ============================== 9 | 10 | - Default: ``10`` 11 | 12 | This tells the pagiante tag how many objects are normally displayed in a page (overwriteable by templatetag). 13 | 14 | 15 | ``ENDLESS_PAGINATION_PAGE_LABEL`` 16 | ================================= 17 | 18 | - Default: ``'page'`` 19 | 20 | This is the the querystring key of the page number (e.g. http://example.com?page=2). 21 | 22 | 23 | ``SIMPLE_PAGINATION_NEXT_LABEL`` 24 | ================================ 25 | 26 | - Default: ``''`` 27 | 28 | This is the default label for the previous page link. 29 | 30 | 31 | ``SIMPLE_PAGINATION_PREVIOUS_LABEL`` 32 | ===================================== 33 | 34 | - Default ``''`` 35 | 36 | This is the default label for the next page link. 37 | 38 | 39 | ``SIMPLE_PAGINATION_LAST_LABEL`` 40 | ================================= 41 | 42 | - Default: ``''`` 43 | 44 | This is the default label for the last page link. 45 | 46 | ``SIMPLE_PAGINATION_FIRST_LABEL`` 47 | ================================= 48 | 49 | - Default: ``''`` 50 | 51 | This is the default label for the first page link. 52 | -------------------------------------------------------------------------------- /docs/simple_pagination.rst: -------------------------------------------------------------------------------- 1 | Simple pagination 2 | ===================== 3 | 4 | Simple pagination is nothing but a basic Digg-style pagination of queryset objects. It is really easy to implement. All you have to do is modifying the template, e.g.: 5 | 6 | .. code-block:: html+django 7 | 8 | {% load paginate %} 9 | 10 | {% paginate items %} 11 | {% for item in items %} 12 | {# your code to show the item #} 13 | {% endfor %} 14 | {% show_pageitems %} 15 | 16 | That's it! As seen, the :ref:`templatetags-paginate` template tag takes care of 17 | customizing the given queryset and the current template context. The 18 | :ref:`templatetags-show_pageitems` one displays the page links allowing for 19 | navigation to other pages including previous, next, first and last links. -------------------------------------------------------------------------------- /docs/start.rst: -------------------------------------------------------------------------------- 1 | Getting started 2 | =============== 3 | 4 | Requirements 5 | ~~~~~~~~~~~~ 6 | 7 | ====== ==================== 8 | Python >= 3.5 9 | Django >= 2.1 10 | jQuery >= 1.7 11 | ====== ==================== 12 | 13 | Installation 14 | ~~~~~~~~~~~~ 15 | 16 | The Git repository can be cloned with this command:: 17 | 18 | git clone https://github.com/MicroPyramid/django-simple-pagination.git 19 | 20 | The ``simple_pagination`` package, included in the distribution, should be 21 | placed on the ``PYTHONPATH``. 22 | 23 | Otherwise you can just ``easy_install -Z django-simple-pagination`` 24 | or ``pip install django-simple-pagination``. 25 | 26 | Settings 27 | ~~~~~~~~ 28 | 29 | Add the request context processor to your *settings.py*, e.g.:: 30 | 31 | from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS 32 | TEMPLATE_CONTEXT_PROCESSORS += ( 33 | 'django.core.context_processors.request', 34 | ) 35 | 36 | Add ``'simple_pagination'`` to the ``INSTALLED_APPS`` to your *settings.py*. 37 | 38 | See the :doc:`settings` section for other settings. 39 | 40 | Quickstart 41 | ~~~~~~~~~~ 42 | 43 | Given a template like this: 44 | 45 | .. code-block:: html+django 46 | 47 | {% for item in items %} 48 | {# your code to show the item #} 49 | {% endfor %} 50 | 51 | you can use simple Digg-style pagination to display objects just by adding: 52 | 53 | .. code-block:: html+django 54 | 55 | {% load paginate %} 56 | 57 | {% paginate items %} 58 | {% for item in items %} 59 | {# your code to show the item #} 60 | {% endfor %} 61 | {% show_pageitems %} 62 | 63 | Done. 64 | 65 | This is just a basic example. To continue exploring all the Django Simple 66 | Pagination features, have a look at :doc:`simple_pagination`. -------------------------------------------------------------------------------- /docs/templatetags_reference.rst: -------------------------------------------------------------------------------- 1 | Templatetags reference 2 | ====================== 3 | 4 | .. _templatetags-paginate: 5 | 6 | paginate 7 | ~~~~~~~~ 8 | 9 | Usage: 10 | 11 | .. code-block:: html+django 12 | 13 | {% paginate items %} 14 | 15 | After this call, the *items* variable in the template context is replaced 16 | by only the entries of the current page. 17 | 18 | You can also keep your *items* original variable (usually a queryset) 19 | and add to the context another name that refers to items of the current page, 20 | e.g.: 21 | 22 | .. code-block:: html+django 23 | 24 | {% paginate items as page_items %} 25 | 26 | The *as* argument is also useful when a nested context variable is provided 27 | as queryset. 28 | 29 | The number of paginated items is taken from SIMPLE_PAGINATION_PER_PAGE setting , but you can 30 | override the default locally, e.g.: 31 | 32 | .. code-block:: html+django 33 | 34 | {% paginate 20 items %} 35 | 36 | Of course you can mix it all: 37 | 38 | .. code-block:: html+django 39 | 40 | {% paginate 20 items as paginated_items %} 41 | 42 | .. _templatetags-show_pageitems: 43 | 44 | show_pageitems 45 | ~~~~~~~~~~~~~~ 46 | 47 | Usage: 48 | 49 | .. code-block:: html+django 50 | 51 | {% show_pageitems %} 52 | 53 | This call in the template will give a digg-style page sequence that contain following values with other page links: 54 | 55 | - *'previous'*: will display the previous page in that position; 56 | - *'next'*: will display the next page in that position; 57 | - *'first'*: will display the first page as an arrow; 58 | - *'last'*: will display the last page as an arrow; 59 | 60 | This must be called after `paginate`_. 61 | -------------------------------------------------------------------------------- /sandbox/manage.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import os 3 | import sys 4 | 5 | if __name__ == "__main__": 6 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "test_pagination.settings") 7 | try: 8 | from django.core.management import execute_from_command_line 9 | except ImportError: 10 | # The above import may fail for some other reason. Ensure that the 11 | # issue is really that Django is missing to avoid masking other 12 | # exceptions on Python 2. 13 | try: 14 | import django 15 | except ImportError: 16 | raise ImportError( 17 | "Couldn't import Django. Are you sure it's installed and " 18 | "available on your PYTHONPATH environment variable? Did you " 19 | "forget to activate a virtual environment?" 20 | ) 21 | raise 22 | execute_from_command_line(sys.argv) 23 | -------------------------------------------------------------------------------- /sandbox/requirements.txt: -------------------------------------------------------------------------------- 1 | Django>=2.1 2 | django-simple-pagination==1.3 3 | -------------------------------------------------------------------------------- /sandbox/sample/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MicroPyramid/django-simple-pagination/dce9941df940d864c0533d732adb2602e4045209/sandbox/sample/__init__.py -------------------------------------------------------------------------------- /sandbox/sample/admin.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import unicode_literals 3 | 4 | from django.contrib import admin 5 | 6 | # Register your models here. 7 | -------------------------------------------------------------------------------- /sandbox/sample/apps.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import unicode_literals 3 | 4 | from django.apps import AppConfig 5 | 6 | 7 | class SampleConfig(AppConfig): 8 | name = 'sample' 9 | -------------------------------------------------------------------------------- /sandbox/sample/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MicroPyramid/django-simple-pagination/dce9941df940d864c0533d732adb2602e4045209/sandbox/sample/migrations/__init__.py -------------------------------------------------------------------------------- /sandbox/sample/models.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import unicode_literals 3 | 4 | from django.db import models 5 | 6 | # Create your models here. 7 | -------------------------------------------------------------------------------- /sandbox/sample/tests.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import unicode_literals 3 | 4 | from django.test import TestCase 5 | 6 | # Create your tests here. 7 | -------------------------------------------------------------------------------- /sandbox/sample/views.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | from __future__ import unicode_literals 3 | 4 | from django.shortcuts import render 5 | from django.contrib.auth.models import User 6 | 7 | 8 | # Create your views here. 9 | def users(request): 10 | users = User.objects.all() 11 | return render(request, 'users.html', {'users': users}) 12 | -------------------------------------------------------------------------------- /sandbox/simple_pagination/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MicroPyramid/django-simple-pagination/dce9941df940d864c0533d732adb2602e4045209/sandbox/simple_pagination/__init__.py -------------------------------------------------------------------------------- /sandbox/simple_pagination/admin.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MicroPyramid/django-simple-pagination/dce9941df940d864c0533d732adb2602e4045209/sandbox/simple_pagination/admin.py -------------------------------------------------------------------------------- /sandbox/simple_pagination/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MicroPyramid/django-simple-pagination/dce9941df940d864c0533d732adb2602e4045209/sandbox/simple_pagination/migrations/__init__.py -------------------------------------------------------------------------------- /sandbox/simple_pagination/models.py: -------------------------------------------------------------------------------- 1 | """Ephemeral models used to represent a page and a list of pages.""" 2 | 3 | from __future__ import unicode_literals 4 | 5 | from django.template import loader 6 | from django.utils.encoding import iri_to_uri 7 | 8 | from simple_pagination import settings 9 | from simple_pagination import utils 10 | 11 | 12 | # Page templates cache. 13 | _template_cache = {} 14 | 15 | 16 | class EndlessPage(): 17 | """A page link representation. 18 | 19 | Interesting attributes: 20 | 21 | - *self.number*: the page number; 22 | - *self.label*: the label of the link 23 | (usually the page number as string); 24 | - *self.url*: the url of the page (starting with "?"); 25 | - *self.path*: the path of the page; 26 | - *self.is_current*: return True if page is the current page displayed; 27 | - *self.is_first*: return True if page is the first page; 28 | - *self.is_last*: return True if page is the last page. 29 | """ 30 | 31 | def __init__(self, request, number, current_number, *args, **kwargs): 32 | total_number = kwargs.get('total_number') 33 | querystring_key = kwargs.get('querystring_key', 'page') 34 | label = kwargs.get('label', None) 35 | default_number = kwargs.get('default_number', 1) 36 | override_path = kwargs.get('override_path', None) 37 | self._request = request 38 | self.number = number 39 | self.label = str(number) if label is None else label 40 | self.querystring_key = querystring_key 41 | 42 | self.is_current = number == current_number 43 | self.is_first = number == 1 44 | self.is_last = number == total_number 45 | 46 | self.url = utils.get_querystring_for_page( 47 | request, number, self.querystring_key, 48 | default_number=default_number) 49 | path = iri_to_uri(override_path or request.path) 50 | self.path = '{0}{1}'.format(path, self.url) 51 | 52 | def __str__(self): 53 | """Render the page as a link.""" 54 | context = { 55 | 'add_nofollow': False, 56 | 'page': self, 57 | 'querystring_key': self.querystring_key, 58 | } 59 | if self.is_current: 60 | template_name = 'simple/current_link.html' 61 | else: 62 | template_name = 'simple/page_link.html' 63 | template = _template_cache.setdefault( 64 | template_name, loader.get_template(template_name)) 65 | return template.render(context) 66 | 67 | 68 | class PageList(): 69 | """A sequence of endless pages.""" 70 | 71 | def __init__(self, request, page, querystring_key, **kwargs): 72 | default_number = kwargs.get('default_number', None) 73 | override_path = kwargs.get('override_path', None) 74 | self._request = request 75 | self._page = page 76 | if default_number is None: 77 | self._default_number = 1 78 | else: 79 | self._default_number = int(default_number) 80 | self._querystring_key = querystring_key 81 | self._override_path = override_path 82 | 83 | def _endless_page(self, number, label=None): 84 | """Factory function that returns a *EndlessPage* instance. 85 | 86 | This method works just like a partial constructor. 87 | """ 88 | return EndlessPage( 89 | self._request, 90 | number, 91 | self._page.number, 92 | len(self), 93 | self._querystring_key, 94 | label=label, 95 | default_number=self._default_number, 96 | override_path=self._override_path, 97 | ) 98 | 99 | def __getitem__(self, value): 100 | # The type conversion is required here because in templates Django 101 | # performs a dictionary lookup before the attribute lokups 102 | # (when a dot is encountered). 103 | try: 104 | value = int(value) 105 | except (TypeError, ValueError): 106 | # A TypeError says to django to continue with an attribute lookup. 107 | raise TypeError 108 | if 1 <= value <= len(self): 109 | return self._endless_page(value) 110 | raise IndexError('page list index out of range') 111 | 112 | def __len__(self): 113 | """The length of the sequence is the total number of pages.""" 114 | return self._page.paginator.num_pages 115 | 116 | def __iter__(self): 117 | """Iterate over all the endless pages (from first to last).""" 118 | for i in range(len(self)): 119 | yield self[i + 1] 120 | 121 | def __str__(self): 122 | """Return a rendered Digg-style pagination (by default). 123 | 124 | The callable *settings.PAGE_LIST_CALLABLE* can be used to customize 125 | how the pages are displayed. The callable takes the current page number 126 | and the total number of pages, and must return a sequence of page 127 | numbers that will be displayed. The sequence can contain other values: 128 | 129 | - *'previous'*: will display the previous page in that position; 130 | - *'next'*: will display the next page in that position; 131 | - *'first'*: will display the first page as an arrow; 132 | - *'last'*: will display the last page as an arrow; 133 | - *None*: a separator will be displayed in that position. 134 | 135 | Here is an example of custom calable that displays the previous page, 136 | then the first page, then a separator, then the current page, and 137 | finally the last page:: 138 | 139 | def get_page_numbers(current_page, num_pages): 140 | return ('previous', 1, None, current_page, 'last') 141 | 142 | If *settings.PAGE_LIST_CALLABLE* is None an internal callable is used, 143 | generating a Digg-style pagination. The value of 144 | *settings.PAGE_LIST_CALLABLE* can also be a dotted path to a callable. 145 | """ 146 | if len(self) > 1: 147 | pages_callable = utils.get_page_numbers 148 | pages = [] 149 | for item in pages_callable(self._page.number, len(self)): 150 | if item is None: 151 | pages.append(None) 152 | elif item == 'previous': 153 | pages.append(self.previous()) 154 | elif item == 'next': 155 | pages.append(self.next()) 156 | elif item == 'first': 157 | pages.append(self.first_as_arrow()) 158 | elif item == 'last': 159 | pages.append(self.last_as_arrow()) 160 | else: 161 | pages.append(self[item]) 162 | return loader.render_to_string('simple/show_pages.html', {'pages': pages}) 163 | return '' 164 | 165 | def current(self): 166 | """Return the current page.""" 167 | return self._endless_page(self._page.number) 168 | 169 | def current_start_index(self): 170 | """Return the 1-based index of the first item on the current page.""" 171 | return self._page.start_index() 172 | 173 | def current_end_index(self): 174 | """Return the 1-based index of the last item on the current page.""" 175 | return self._page.end_index() 176 | 177 | def total_count(self): 178 | """Return the total number of objects, across all pages.""" 179 | return self._page.paginator.count 180 | 181 | def first(self, label=None): 182 | """Return the first page.""" 183 | return self._endless_page(1, label=label) 184 | 185 | def last(self, label=None): 186 | """Return the last page.""" 187 | return self._endless_page(len(self), label=label) 188 | 189 | def first_as_arrow(self): 190 | """Return the first page as an arrow. 191 | 192 | The page label (arrow) is defined in ``settings.FIRST_LABEL``. 193 | """ 194 | return self.first(label=settings.FIRST_LABEL) 195 | 196 | def last_as_arrow(self): 197 | """Return the last page as an arrow. 198 | 199 | The page label (arrow) is defined in ``settings.LAST_LABEL``. 200 | """ 201 | return self.last(label=settings.LAST_LABEL) 202 | 203 | def previous(self): 204 | """Return the previous page. 205 | 206 | The page label is defined in ``settings.PREVIOUS_LABEL``. 207 | Return an empty string if current page is the first. 208 | """ 209 | if self._page.has_previous(): 210 | return self._endless_page( 211 | self._page.previous_page_number(), 212 | label=settings.PREVIOUS_LABEL) 213 | return '' 214 | 215 | def next(self): 216 | """Return the next page. 217 | 218 | The page label is defined in ``settings.NEXT_LABEL``. 219 | Return an empty string if current page is the last. 220 | """ 221 | if self._page.has_next(): 222 | return self._endless_page( 223 | self._page.next_page_number(), 224 | label=settings.NEXT_LABEL) 225 | return '' 226 | 227 | def paginated(self): 228 | """Return True if this page list contains more than one page.""" 229 | return len(self) > 1 230 | 231 | 232 | class ShowItems(): 233 | """A page link representation. 234 | 235 | Interesting attributes: 236 | 237 | - *self.number*: the page number; 238 | - *self.label*: the label of the link 239 | (usually the page number as string); 240 | - *self.url*: the url of the page (starting with "?"); 241 | - *self.path*: the path of the page; 242 | - *self.is_current*: return True if page is the current page displayed; 243 | - *self.is_first*: return True if page is the first page; 244 | - *self.is_last*: return True if page is the last page. 245 | """ 246 | 247 | def __init__(self, request, page, querystring_key, **kwargs): 248 | default_number = kwargs.get('default_number', None) 249 | override_path = kwargs.get('override_path', None) 250 | self._request = request 251 | self._page = page 252 | if default_number is None: 253 | self._default_number = 1 254 | else: 255 | self._default_number = int(default_number) 256 | self._querystring_key = querystring_key 257 | self._override_path = override_path 258 | 259 | def __str__(self): 260 | """Render the page as a link.""" 261 | str_data = "Showing " 262 | if self._page.paginator.count == 1: 263 | str_data += str(1) 264 | str_data = str_data + " to " + str(len(self._page.object_list)) + " of " + str(len(self._page.object_list)) 265 | else: 266 | if self._page.number == 1: 267 | str_data += str(1) 268 | if self._page.paginator.per_page == str(self._page.paginator.count): 269 | str_data = str_data + " to " + str(self._page.paginator.per_page) + " of " + str(self._page.paginator.count) 270 | else: 271 | str_data = str_data + " to " + str(len(self._page.object_list)) + " of " + str(self._page.paginator.count) 272 | else: 273 | if self._page.has_next(): 274 | str_data += "".join(map(str, [ 275 | (self._page.paginator.per_page * self._page.previous_page_number()) + 1, 276 | " to ", 277 | self._page.paginator.per_page * self._page.number, 278 | " of ", 279 | self._page.paginator.count 280 | ])) 281 | else: 282 | str_data += "".join(map(str, [ 283 | self._page.paginator.per_page * self._page.previous_page_number() + 1, 284 | " to ", 285 | self._page.paginator.count, 286 | " of ", 287 | self._page.paginator.count 288 | ])) 289 | 290 | return str_data + " items" 291 | -------------------------------------------------------------------------------- /sandbox/simple_pagination/settings.py: -------------------------------------------------------------------------------- 1 | from django.conf import settings 2 | 3 | PER_PAGE = getattr(settings, 'SIMPLE_PAGINATION_PER_PAGE', 10) 4 | PAGE_LABEL = getattr(settings, 'SIMPLE_PAGINATION_PAGE_LABEL', 'page') 5 | NEXT_LABEL = getattr( 6 | settings, 'SIMPLE_PAGINATION_NEXT_LABEL', '') 7 | PREVIOUS_LABEL = getattr( 8 | settings, 'SIMPLE_PAGINATION_PREVIOUS_LABEL', '') 9 | LAST_LABEL = getattr( 10 | settings, 'SIMPLE_PAGINATION_LAST_LABEL', '') 11 | FIRST_LABEL = getattr( 12 | settings, 'SIMPLE_PAGINATION_FIRST_LABEL', '') 13 | -------------------------------------------------------------------------------- /sandbox/simple_pagination/templates/simple/current_link.html: -------------------------------------------------------------------------------- 1 |
  • {{ page.label|safe }}
  • -------------------------------------------------------------------------------- /sandbox/simple_pagination/templates/simple/page_link.html: -------------------------------------------------------------------------------- 1 |
  • {{ page.label|safe }}
  • -------------------------------------------------------------------------------- /sandbox/simple_pagination/templates/simple/show_pages.html: -------------------------------------------------------------------------------- 1 |
      2 | {% for page in pages %}{{page}}{% endfor %} 3 |
    4 | -------------------------------------------------------------------------------- /sandbox/simple_pagination/templatetags/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MicroPyramid/django-simple-pagination/dce9941df940d864c0533d732adb2602e4045209/sandbox/simple_pagination/templatetags/__init__.py -------------------------------------------------------------------------------- /sandbox/simple_pagination/templatetags/paginate.py: -------------------------------------------------------------------------------- 1 | """Django Endless Pagination template tags.""" 2 | 3 | import re 4 | 5 | from django import template 6 | from simple_pagination import settings 7 | from django.core.paginator import ( 8 | EmptyPage, 9 | Paginator, 10 | ) 11 | from simple_pagination import utils 12 | from simple_pagination import models 13 | 14 | 15 | PAGINATE_EXPRESSION = re.compile(r""" 16 | ^ # Beginning of line. 17 | (((?P\w+)\,)?(?P\w+)\s+)? # First page, per page. 18 | (?P[\.\w]+) # Objects / queryset. 19 | (\s+starting\s+from\s+page\s+(?P[\-]?\d+|\w+))? # Page start. 20 | (\s+using\s+(?P[\"\'\-\w]+))? # Querystring key. 21 | (\s+with\s+(?P[\"\'\/\w]+))? # Override path. 22 | (\s+as\s+(?P\w+))? # Context variable name. 23 | $ # End of line. 24 | """, re.VERBOSE) 25 | SHOW_CURRENT_NUMBER_EXPRESSION = re.compile(r""" 26 | ^ # Beginning of line. 27 | (starting\s+from\s+page\s+(?P\w+))?\s* # Page start. 28 | (using\s+(?P[\"\'\-\w]+))?\s* # Querystring key. 29 | (as\s+(?P\w+))? # Context variable name. 30 | $ # End of line. 31 | """, re.VERBOSE) 32 | 33 | 34 | register = template.Library() 35 | 36 | 37 | @register.tag 38 | def paginate(_, token, paginator_class=None): 39 | """Paginate objects. 40 | 41 | Usage: 42 | 43 | .. code-block:: html+django 44 | 45 | {% paginate entries %} 46 | 47 | After this call, the *entries* variable in the template context is replaced 48 | by only the entries of the current page. 49 | 50 | You can also keep your *entries* original variable (usually a queryset) 51 | and add to the context another name that refers to entries of the current 52 | page, e.g.: 53 | 54 | .. code-block:: html+django 55 | 56 | {% paginate entries as page_entries %} 57 | 58 | The *as* argument is also useful when a nested context variable is provided 59 | as queryset. In this case, and only in this case, the resulting variable 60 | name is mandatory, e.g.: 61 | 62 | .. code-block:: html+django 63 | 64 | {% paginate entries.all as entries %} 65 | 66 | The number of paginated entries is taken from settings, but you can 67 | override the default locally, e.g.: 68 | 69 | .. code-block:: html+django 70 | 71 | {% paginate 20 entries %} 72 | 73 | Of course you can mix it all: 74 | 75 | .. code-block:: html+django 76 | 77 | {% paginate 20 entries as paginated_entries %} 78 | 79 | By default, the first page is displayed the first time you load the page, 80 | but you can change this, e.g.: 81 | 82 | .. code-block:: html+django 83 | 84 | {% paginate entries starting from page 3 %} 85 | 86 | When changing the default page, it is also possible to reference the last 87 | page (or the second last page, and so on) by using negative indexes, e.g: 88 | 89 | .. code-block:: html+django 90 | 91 | {% paginate entries starting from page -1 %} 92 | 93 | This can be also achieved using a template variable that was passed to the 94 | context, e.g.: 95 | 96 | .. code-block:: html+django 97 | 98 | {% paginate entries starting from page page_number %} 99 | 100 | If the passed page number does not exist, the first page is displayed. 101 | 102 | If you have multiple paginations in the same page, you can change the 103 | querydict key for the single pagination, e.g.: 104 | 105 | .. code-block:: html+django 106 | 107 | {% paginate entries using article_page %} 108 | 109 | In this case *article_page* is intended to be a context variable, but you 110 | can hardcode the key using quotes, e.g.: 111 | 112 | .. code-block:: html+django 113 | 114 | {% paginate entries using 'articles_at_page' %} 115 | 116 | Again, you can mix it all (the order of arguments is important): 117 | 118 | .. code-block:: html+django 119 | 120 | {% paginate 20 entries 121 | starting from page 3 using page_key as paginated_entries %} 122 | 123 | Additionally you can pass a path to be used for the pagination: 124 | 125 | .. code-block:: html+django 126 | 127 | {% paginate 20 entries 128 | using page_key with pagination_url as paginated_entries %} 129 | 130 | This way you can easily create views acting as API endpoints, and point 131 | your Ajax calls to that API. In this case *pagination_url* is considered a 132 | context variable, but it is also possible to hardcode the URL, e.g.: 133 | 134 | .. code-block:: html+django 135 | 136 | {% paginate 20 entries with "/mypage/" %} 137 | 138 | If you want the first page to contain a different number of items than 139 | subsequent pages, you can separate the two values with a comma, e.g. if 140 | you want 3 items on the first page and 10 on other pages: 141 | 142 | .. code-block:: html+django 143 | 144 | {% paginate 3,10 entries %} 145 | 146 | You must use this tag before calling the {% show_more %} one. 147 | """ 148 | # Validate arguments. 149 | try: 150 | tag_name, tag_args = token.contents.split(None, 1) 151 | except ValueError: 152 | msg = '%r tag requires arguments' % token.contents.split()[0] 153 | raise template.TemplateSyntaxError(msg) 154 | 155 | # Use a regexp to catch args. 156 | match = PAGINATE_EXPRESSION.match(tag_args) 157 | if match is None: 158 | msg = 'Invalid arguments for %r tag' % tag_name 159 | raise template.TemplateSyntaxError(msg) 160 | 161 | # Retrieve objects. 162 | kwargs = match.groupdict() 163 | objects = kwargs.pop('objects') 164 | 165 | # The variable name must be present if a nested context variable is passed. 166 | if '.' in objects and kwargs['var_name'] is None: 167 | msg = ( 168 | '%(tag)r tag requires a variable name `as` argumnent if the ' 169 | 'queryset is provided as a nested context variable (%(objects)s). ' 170 | 'You must either pass a direct queryset (e.g. taking advantage ' 171 | 'of the `with` template tag) or provide a new variable name to ' 172 | 'store the resulting queryset (e.g. `%(tag)s %(objects)s as ' 173 | 'objects`).' 174 | ) % {'tag': tag_name, 'objects': objects} 175 | raise template.TemplateSyntaxError(msg) 176 | 177 | # Call the node. 178 | return PaginateNode(paginator_class, objects, **kwargs) 179 | 180 | 181 | class PaginateNode(template.Node): 182 | """Add to context the objects of the current page. 183 | 184 | Also add the Django paginator's *page* object. 185 | """ 186 | 187 | def __init__(self, paginator_class, objects, **kwargs): 188 | first_page = kwargs.get('first_page', None) 189 | per_page = kwargs.get('per_page', None) 190 | var_name = kwargs.get('var_name', None) 191 | number = kwargs.get('number', None) 192 | key = kwargs.get('key', None) 193 | override_path = kwargs.get('override_path', None) 194 | self.paginator = paginator_class or Paginator 195 | self.objects = template.Variable(objects) 196 | 197 | # If *var_name* is not passed, then the queryset name will be used. 198 | self.var_name = objects if var_name is None else var_name 199 | 200 | # If *per_page* is not passed then the default value from settings 201 | # will be used. 202 | self.per_page_variable = None 203 | if per_page is None: 204 | self.per_page = settings.PER_PAGE 205 | elif per_page.isdigit(): 206 | self.per_page = int(per_page) 207 | else: 208 | self.per_page_variable = template.Variable(per_page) 209 | 210 | # Handle first page: if it is not passed then *per_page* is used. 211 | self.first_page_variable = None 212 | if first_page is None: 213 | self.first_page = None 214 | elif first_page.isdigit(): 215 | self.first_page = int(first_page) 216 | else: 217 | self.first_page_variable = template.Variable(first_page) 218 | 219 | # Handle page number when it is not specified in querystring. 220 | self.page_number_variable = None 221 | if number is None: 222 | self.page_number = 1 223 | else: 224 | try: 225 | self.page_number = int(number) 226 | except ValueError: 227 | self.page_number_variable = template.Variable(number) 228 | 229 | # Set the querystring key attribute. 230 | self.querystring_key_variable = None 231 | if key is None: 232 | self.querystring_key = settings.PAGE_LABEL 233 | elif key[0] in ('"', "'") and key[-1] == key[0]: 234 | self.querystring_key = key[1:-1] 235 | else: 236 | self.querystring_key_variable = template.Variable(key) 237 | 238 | # Handle *override_path*. 239 | self.override_path_variable = None 240 | if override_path is None: 241 | self.override_path = None 242 | elif ( 243 | override_path[0] in ('"', "'") and 244 | override_path[-1] == override_path[0]): 245 | self.override_path = override_path[1:-1] 246 | else: 247 | self.override_path_variable = template.Variable(override_path) 248 | 249 | def render(self, context): 250 | # Handle page number when it is not specified in querystring. 251 | if self.page_number_variable is None: 252 | default_number = self.page_number 253 | else: 254 | default_number = int(self.page_number_variable.resolve(context)) 255 | 256 | # Calculate the number of items to show on each page. 257 | if self.per_page_variable is None: 258 | per_page = self.per_page 259 | else: 260 | per_page = int(self.per_page_variable.resolve(context)) 261 | 262 | # User can override the querystring key to use in the template. 263 | # The default value is defined in the settings file. 264 | if self.querystring_key_variable is None: 265 | querystring_key = self.querystring_key 266 | else: 267 | querystring_key = self.querystring_key_variable.resolve(context) 268 | 269 | # Retrieve the override path if used. 270 | if self.override_path_variable is None: 271 | override_path = self.override_path 272 | else: 273 | override_path = self.override_path_variable.resolve(context) 274 | 275 | # Retrieve the queryset and create the paginator object. 276 | objects = self.objects.resolve(context) 277 | paginator = self.paginator( 278 | objects, per_page) 279 | 280 | # Normalize the default page number if a negative one is provided. 281 | if default_number < 0: 282 | default_number = utils.normalize_page_number( 283 | default_number, paginator.page_range) 284 | 285 | # The current request is used to get the requested page number. 286 | page_number = utils.get_page_number_from_request( 287 | context['request'], querystring_key, default=default_number) 288 | 289 | # Get the page. 290 | try: 291 | page = paginator.page(page_number) 292 | except EmptyPage: 293 | page = paginator.page(1) 294 | 295 | # Populate the context with required data. 296 | data = { 297 | 'default_number': default_number, 298 | 'override_path': override_path, 299 | 'page': page, 300 | 'querystring_key': querystring_key, 301 | } 302 | context.update({'endless': data, self.var_name: page.object_list}) 303 | return '' 304 | 305 | 306 | @register.tag 307 | def show_pages(_, token): 308 | """Show page links. 309 | 310 | Usage: 311 | 312 | .. code-block:: html+django 313 | 314 | {% show_pages %} 315 | 316 | It is just a shortcut for: 317 | 318 | .. code-block:: html+django 319 | 320 | {% get_pages %} 321 | {{ pages }} 322 | 323 | You can set ``ENDLESS_PAGINATION_PAGE_LIST_CALLABLE`` in your *settings.py* 324 | to a callable, or to a dotted path representing a callable, used to 325 | customize the pages that are displayed. 326 | 327 | See the *__unicode__* method of ``endless_pagination.models.PageList`` for 328 | a detailed explanation of how the callable can be used. 329 | 330 | Must be called after ``{% paginate objects %}``. 331 | """ 332 | # Validate args. 333 | if len(token.contents.split()) != 1: 334 | msg = '%r tag takes no arguments' % token.contents.split()[0] 335 | raise template.TemplateSyntaxError(msg) 336 | # Call the node. 337 | return ShowPagesNode() 338 | 339 | 340 | class ShowPagesNode(template.Node): 341 | """Show the pagination.""" 342 | 343 | def render(self, context): 344 | # This template tag could raise a PaginationError: you have to call 345 | # *paginate* or *lazy_paginate* before including the getpages template. 346 | data = utils.get_data_from_context(context) 347 | # Return the string representation of the sequence of pages. 348 | pages = models.PageList( 349 | context['request'], 350 | data['page'], 351 | data['querystring_key'], 352 | default_number=data['default_number'], 353 | override_path=data['override_path'], 354 | ) 355 | return str(pages) 356 | 357 | 358 | @register.tag 359 | def show_pageitems(_, token): 360 | """Show page items. 361 | 362 | Usage: 363 | 364 | .. code-block:: html+django 365 | 366 | {% show_pageitems per_page %} 367 | 368 | """ 369 | # Validate args. 370 | if len(token.contents.split()) != 1: 371 | msg = '%r tag takes no arguments' % token.contents.split()[0] 372 | raise template.TemplateSyntaxError(msg) 373 | # Call the node. 374 | return ShowPageItemsNode() 375 | 376 | 377 | class ShowPageItemsNode(template.Node): 378 | """Show the pagination.""" 379 | 380 | def render(self, context): 381 | # This template tag could raise a PaginationError: you have to call 382 | # *paginate* or *lazy_paginate* before including the getpages template. 383 | data = utils.get_data_from_context(context) 384 | pages = models.ShowItems( 385 | context['request'], 386 | data['page'], 387 | data['querystring_key'], 388 | default_number=data['default_number'], 389 | override_path=data['override_path'], 390 | ) 391 | return str(pages) 392 | -------------------------------------------------------------------------------- /sandbox/simple_pagination/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | from django.template import Template, Context 3 | from django.http import HttpRequest 4 | from simple_pagination.utils import( 5 | normalize_page_number, 6 | get_querystring_for_page, 7 | get_page_numbers, 8 | ) 9 | from simple_pagination.models import EndlessPage, PageList, ShowItems 10 | from django.http import QueryDict 11 | from django.core.paginator import Paginator 12 | 13 | 14 | class PaginateAndShowPageItems(TestCase): 15 | 16 | def test_addition(self): 17 | t = Template( 18 | "{% load paginate %}{% paginate entities %}.{% show_pageitems %} {% paginate 20 entities %} {% show_pages %}") 19 | req = HttpRequest() 20 | c = Context({"entities": range(100), 'request': req}) 21 | val = t.render(c) 22 | self.assertTrue(bool(val)) 23 | 24 | 25 | class NormalizePageNumber(TestCase): 26 | 27 | def test_normalize_page_number(self): 28 | page_number = 1 29 | page_range = range(2) 30 | val = normalize_page_number(page_number, page_range) 31 | self.assertTrue(bool(val)) 32 | page_range = range(1) 33 | val = normalize_page_number(page_number, page_range) 34 | self.assertFalse(bool(val)) 35 | 36 | 37 | class GetQuerystringForPage(TestCase): 38 | 39 | def test_get_querystring_for_page(self): 40 | request = self 41 | request = HttpRequest() 42 | dict = {u"querystring_key": 1, 43 | u"key": 2, 44 | u"page": 3} 45 | qdict = QueryDict('', mutable=True) 46 | qdict.update(dict) 47 | request.GET = qdict 48 | val = get_querystring_for_page(request=request, 49 | page_number=1, 50 | querystring_key="key", 51 | default_number=1) 52 | self.assertTrue(bool(val)) 53 | request.GET = {} 54 | val = get_querystring_for_page(request=request, 55 | page_number=1, 56 | querystring_key="key", 57 | default_number=1) 58 | self.assertFalse(bool(val)) 59 | 60 | 61 | class GetPageNumbers(TestCase): 62 | 63 | def test_get_page_numbers(self): 64 | self.assertTrue(get_page_numbers(current_page=2, num_pages=10)) 65 | self.assertTrue(get_page_numbers(current_page=9, num_pages=10)) 66 | self.assertTrue(get_page_numbers(current_page=1, num_pages=3)) 67 | 68 | 69 | class TestEndlessPage(TestCase): 70 | 71 | def test_endless_page(self): 72 | request = HttpRequest() 73 | epage = EndlessPage(request=request, 74 | number=2, 75 | current_number=2, 76 | total_number=10, 77 | querystring_key='page') 78 | self.assertTrue(epage) 79 | 80 | 81 | class TestPageList(TestCase): 82 | 83 | def test_page_list(self): 84 | request = HttpRequest() 85 | paginator = Paginator(['john', 'paul', 'george', 'ringo'], 3) 86 | page = paginator.page(1) 87 | page.number = lambda: None 88 | setattr(page, 'number', 2) 89 | setattr(page, 'paginator', paginator) 90 | page_list = PageList(request=request, page=page, querystring_key="page") 91 | page_list = PageList(request=request, page=page, querystring_key="page", default_number=1) 92 | page_list._endless_page(number=1) 93 | page_list._endless_page(number=3) 94 | self.assertTrue(page_list[1]) 95 | page_list.next() 96 | self.assertTrue(page_list) 97 | si = ShowItems(request=request, page=page, querystring_key="page") 98 | self.assertTrue(si) 99 | -------------------------------------------------------------------------------- /sandbox/simple_pagination/utils.py: -------------------------------------------------------------------------------- 1 | from __future__ import unicode_literals 2 | import urllib 3 | 4 | from simple_pagination.settings import ( 5 | PAGE_LABEL 6 | ) 7 | 8 | 9 | def get_data_from_context(context): 10 | """Get the django paginator data object from the given *context*. 11 | The context is a dict-like object. If the context key ``endless`` 12 | is not found, a *PaginationError* is raised. 13 | """ 14 | try: 15 | return context['endless'] 16 | except KeyError: 17 | raise Exception('Cannot find endless data in context.') 18 | 19 | 20 | def get_page_number_from_request( 21 | request, querystring_key=PAGE_LABEL, default=1): 22 | """Retrieve the current page number from *GET* or *POST* data. 23 | If the page does not exists in *request*, or is not a number, 24 | then *default* number is returned. 25 | """ 26 | try: 27 | return int(request.GET[querystring_key]) 28 | except (KeyError, TypeError, ValueError): 29 | return default 30 | 31 | 32 | def get_page_numbers(current_page, num_pages): 33 | """Default callable for page listing. 34 | Produce a Digg-style pagination. 35 | """ 36 | 37 | if current_page <= 2: 38 | start_page = 1 39 | else: 40 | start_page = current_page - 2 41 | 42 | if num_pages <= 4: 43 | end_page = num_pages 44 | else: 45 | end_page = start_page + 4 46 | if end_page > num_pages: 47 | end_page = num_pages 48 | 49 | pages = [] 50 | if current_page != 1: 51 | pages.append('first') 52 | pages.append('previous') 53 | pages.extend([i for i in range(start_page, end_page + 1)]) 54 | if current_page != num_pages: 55 | pages.append('next') 56 | pages.append('last') 57 | return pages 58 | 59 | 60 | def get_querystring_for_page( 61 | request, page_number, querystring_key, default_number=1): 62 | """Return a querystring pointing to *page_number*.""" 63 | querydict = request.GET.copy() 64 | querydict[querystring_key] = page_number 65 | # For the default page number (usually 1) the querystring is not required. 66 | if page_number == default_number: 67 | del querydict[querystring_key] 68 | if 'querystring_key' in querydict: 69 | del querydict['querystring_key'] 70 | if querydict: 71 | return '?' + urllib.parse.urlencode(querydict) 72 | return '' 73 | 74 | 75 | def normalize_page_number(page_number, page_range): 76 | """Handle a negative *page_number*. 77 | Return a positive page number contained in *page_range*. 78 | If the negative index is out of range, return the page number 1. 79 | """ 80 | try: 81 | return page_range[page_number] 82 | except IndexError: 83 | return page_range[0] 84 | -------------------------------------------------------------------------------- /sandbox/templates/users.html: -------------------------------------------------------------------------------- 1 | {% load paginate %} 2 | {% if per_page %} 3 | {% paginate per_page users %} 4 | {% else %} 5 | {% paginate 10 users %} 6 | {% endif %} 7 | 8 |
    9 | {% show_pageitems %} 10 |
    11 | 12 |

    Users List

    13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | {% for user in users %} 23 | 24 | 25 | 26 | 28 | 29 | {% endfor %} 30 | 31 |
    NoEmailUsername
    {{ forloop.counter }}{{ user.email }}{{ user.username }} 27 |
    32 | 35 | 36 | -------------------------------------------------------------------------------- /sandbox/test_pagination/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MicroPyramid/django-simple-pagination/dce9941df940d864c0533d732adb2602e4045209/sandbox/test_pagination/__init__.py -------------------------------------------------------------------------------- /sandbox/test_pagination/settings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Django settings for test_pagination project. 3 | 4 | Generated by 'django-admin startproject' using Django 1.11. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/1.11/topics/settings/ 8 | 9 | For the full list of settings and their values, see 10 | https://docs.djangoproject.com/en/1.11/ref/settings/ 11 | """ 12 | 13 | import os 14 | 15 | # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 16 | BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 17 | 18 | 19 | # Quick-start development settings - unsuitable for production 20 | # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ 21 | 22 | # SECURITY WARNING: keep the secret key used in production secret! 23 | SECRET_KEY = 'o04uf+ee_+u+rck@x+vw$ueem=tfurbnmj-$op(31i$iuuyx^a' 24 | 25 | # SECURITY WARNING: don't run with debug turned on in production! 26 | DEBUG = True 27 | 28 | ALLOWED_HOSTS = [] 29 | 30 | 31 | # Application definition 32 | 33 | INSTALLED_APPS = [ 34 | 'django.contrib.admin', 35 | 'django.contrib.auth', 36 | 'django.contrib.contenttypes', 37 | 'django.contrib.sessions', 38 | 'django.contrib.messages', 39 | 'django.contrib.staticfiles', 40 | 'simple_pagination', 41 | ] 42 | 43 | MIDDLEWARE = [ 44 | 'django.middleware.security.SecurityMiddleware', 45 | 'django.contrib.sessions.middleware.SessionMiddleware', 46 | 'django.middleware.common.CommonMiddleware', 47 | 'django.middleware.csrf.CsrfViewMiddleware', 48 | 'django.contrib.auth.middleware.AuthenticationMiddleware', 49 | 'django.contrib.messages.middleware.MessageMiddleware', 50 | 'django.middleware.clickjacking.XFrameOptionsMiddleware', 51 | ] 52 | 53 | ROOT_URLCONF = 'test_pagination.urls' 54 | 55 | TEMPLATES = [ 56 | { 57 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 58 | 'DIRS': [], 59 | 'APP_DIRS': True, 60 | 'OPTIONS': { 61 | 'context_processors': [ 62 | 'django.template.context_processors.debug', 63 | 'django.template.context_processors.request', 64 | 'django.contrib.auth.context_processors.auth', 65 | 'django.contrib.messages.context_processors.messages', 66 | ], 67 | }, 68 | }, 69 | ] 70 | 71 | WSGI_APPLICATION = 'test_pagination.wsgi.application' 72 | 73 | 74 | # Database 75 | # https://docs.djangoproject.com/en/1.11/ref/settings/#databases 76 | 77 | DATABASES = { 78 | 'default': { 79 | 'ENGINE': 'django.db.backends.sqlite3', 80 | 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 81 | } 82 | } 83 | 84 | 85 | # Password validation 86 | # https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators 87 | 88 | AUTH_PASSWORD_VALIDATORS = [ 89 | { 90 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 91 | }, 92 | { 93 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 94 | }, 95 | { 96 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 97 | }, 98 | { 99 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 100 | }, 101 | ] 102 | 103 | 104 | # Internationalization 105 | # https://docs.djangoproject.com/en/1.11/topics/i18n/ 106 | 107 | LANGUAGE_CODE = 'en-us' 108 | 109 | TIME_ZONE = 'UTC' 110 | 111 | USE_I18N = True 112 | 113 | USE_L10N = True 114 | 115 | USE_TZ = True 116 | 117 | 118 | # Static files (CSS, JavaScript, Images) 119 | # https://docs.djangoproject.com/en/1.11/howto/static-files/ 120 | 121 | STATIC_URL = '/static/' 122 | TEMPLATES = [ 123 | { 124 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 125 | 'DIRS': [BASE_DIR + "/templates"], 126 | 'APP_DIRS': True, 127 | 'OPTIONS': { 128 | 'context_processors': [ 129 | 'django.template.context_processors.debug', 130 | 'django.template.context_processors.request', 131 | 'django.contrib.auth.context_processors.auth', 132 | 'django.contrib.messages.context_processors.messages', 133 | ], 134 | }, 135 | }, 136 | ] 137 | -------------------------------------------------------------------------------- /sandbox/test_pagination/urls.py: -------------------------------------------------------------------------------- 1 | """test_pagination URL Configuration 2 | 3 | The `urlpatterns` list routes URLs to views. For more information please see: 4 | https://docs.djangoproject.com/en/1.11/topics/http/urls/ 5 | Examples: 6 | Function views 7 | 1. Add an import: from my_app import views 8 | 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') 9 | Class-based views 10 | 1. Add an import: from other_app.views import Home 11 | 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') 12 | Including another URLconf 13 | 1. Import the include() function: from django.conf.urls import url, include 14 | 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) 15 | """ 16 | from django.conf.urls import url 17 | from django.contrib import admin 18 | from sample.views import users 19 | 20 | urlpatterns = [ 21 | url(r'^admin/', admin.site.urls), 22 | url(r'^users/', users), 23 | 24 | ] 25 | 26 | -------------------------------------------------------------------------------- /sandbox/test_pagination/wsgi.py: -------------------------------------------------------------------------------- 1 | """ 2 | WSGI config for test_pagination project. 3 | 4 | It exposes the WSGI callable as a module-level variable named ``application``. 5 | 6 | For more information on this file, see 7 | https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/ 8 | """ 9 | 10 | import os 11 | 12 | from django.core.wsgi import get_wsgi_application 13 | 14 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "test_pagination.settings") 15 | 16 | application = get_wsgi_application() 17 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import os 2 | from setuptools import setup 3 | 4 | # allow setup.py to be run from any path 5 | os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) 6 | PROJECT_NAME = 'simple_pagination' 7 | 8 | data_files = [] 9 | for dirpath, dirnames, filenames in os.walk(PROJECT_NAME): 10 | for i, dirname in enumerate(dirnames): 11 | if dirname.startswith('.'): 12 | del dirnames[i] 13 | if '__init__.py' in filenames: 14 | continue 15 | elif filenames: 16 | for f in filenames: 17 | data_files.append(os.path.join( 18 | dirpath[len(PROJECT_NAME) + 1:], f)) 19 | 20 | setup( 21 | name='django-simple-pagination', 22 | version='1.4', 23 | packages=['simple_pagination', 'simple_pagination.migrations', 'simple_pagination.templatetags'], 24 | include_package_data=True, 25 | description='A simple pagination app for Django.', 26 | long_description="\n\n".join([open("README.rst").read()]), 27 | url='https://github.com/MicroPyramid/django-simple-pagination', 28 | author='Chaitanya', 29 | author_email='chaitanya@micropyramid.com', 30 | classifiers=[ 31 | 'Environment :: Web Environment', 32 | 'Framework :: Django', 33 | 'Intended Audience :: Developers', 34 | 'Operating System :: OS Independent', 35 | 'License :: OSI Approved :: MIT License', 36 | 'Programming Language :: Python', 37 | 'Programming Language :: Python :: 3.5', 38 | 'Programming Language :: Python :: 3.6', 39 | 'Programming Language :: Python :: 3.7', 40 | 'Topic :: Internet :: WWW/HTTP', 41 | 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 42 | ], 43 | install_requires=[ 44 | "Django==2.1", 45 | ], 46 | ) 47 | -------------------------------------------------------------------------------- /simple_pagination/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MicroPyramid/django-simple-pagination/dce9941df940d864c0533d732adb2602e4045209/simple_pagination/__init__.py -------------------------------------------------------------------------------- /simple_pagination/admin.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MicroPyramid/django-simple-pagination/dce9941df940d864c0533d732adb2602e4045209/simple_pagination/admin.py -------------------------------------------------------------------------------- /simple_pagination/migrations/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MicroPyramid/django-simple-pagination/dce9941df940d864c0533d732adb2602e4045209/simple_pagination/migrations/__init__.py -------------------------------------------------------------------------------- /simple_pagination/models.py: -------------------------------------------------------------------------------- 1 | """Ephemeral models used to represent a page and a list of pages.""" 2 | 3 | from __future__ import unicode_literals 4 | 5 | from django.template import loader 6 | from django.utils.encoding import iri_to_uri 7 | 8 | from simple_pagination import settings 9 | from simple_pagination import utils 10 | 11 | 12 | # Page templates cache. 13 | _template_cache = {} 14 | 15 | 16 | class EndlessPage(): 17 | """A page link representation. 18 | 19 | Interesting attributes: 20 | 21 | - *self.number*: the page number; 22 | - *self.label*: the label of the link 23 | (usually the page number as string); 24 | - *self.url*: the url of the page (starting with "?"); 25 | - *self.path*: the path of the page; 26 | - *self.is_current*: return True if page is the current page displayed; 27 | - *self.is_first*: return True if page is the first page; 28 | - *self.is_last*: return True if page is the last page. 29 | """ 30 | 31 | def __init__(self, request, number, current_number, *args, **kwargs): 32 | total_number = kwargs.get('total_number') 33 | querystring_key = kwargs.get('querystring_key', 'page') 34 | label = kwargs.get('label', None) 35 | default_number = kwargs.get('default_number', 1) 36 | override_path = kwargs.get('override_path', None) 37 | self._request = request 38 | self.number = number 39 | self.label = str(number) if label is None else label 40 | self.querystring_key = querystring_key 41 | 42 | self.is_current = number == current_number 43 | self.is_first = number == 1 44 | self.is_last = number == total_number 45 | 46 | self.url = utils.get_querystring_for_page( 47 | request, number, self.querystring_key, 48 | default_number=default_number) 49 | path = iri_to_uri(override_path or request.path) 50 | self.path = '{0}{1}'.format(path, self.url) 51 | 52 | def __str__(self): 53 | """Render the page as a link.""" 54 | context = { 55 | 'add_nofollow': False, 56 | 'page': self, 57 | 'querystring_key': self.querystring_key, 58 | } 59 | if self.is_current: 60 | template_name = 'simple/current_link.html' 61 | else: 62 | template_name = 'simple/page_link.html' 63 | template = _template_cache.setdefault( 64 | template_name, loader.get_template(template_name)) 65 | return template.render(context) 66 | 67 | 68 | class PageList(): 69 | """A sequence of endless pages.""" 70 | 71 | def __init__(self, request, page, querystring_key, **kwargs): 72 | default_number = kwargs.get('default_number', None) 73 | override_path = kwargs.get('override_path', None) 74 | self._request = request 75 | self._page = page 76 | if default_number is None: 77 | self._default_number = 1 78 | else: 79 | self._default_number = int(default_number) 80 | self._querystring_key = querystring_key 81 | self._override_path = override_path 82 | 83 | def _endless_page(self, number, label=None): 84 | """Factory function that returns a *EndlessPage* instance. 85 | 86 | This method works just like a partial constructor. 87 | """ 88 | return EndlessPage( 89 | self._request, 90 | number, 91 | self._page.number, 92 | len(self), 93 | self._querystring_key, 94 | label=label, 95 | default_number=self._default_number, 96 | override_path=self._override_path, 97 | ) 98 | 99 | def __getitem__(self, value): 100 | # The type conversion is required here because in templates Django 101 | # performs a dictionary lookup before the attribute lokups 102 | # (when a dot is encountered). 103 | try: 104 | value = int(value) 105 | except (TypeError, ValueError): 106 | # A TypeError says to django to continue with an attribute lookup. 107 | raise TypeError 108 | if 1 <= value <= len(self): 109 | return self._endless_page(value) 110 | raise IndexError('page list index out of range') 111 | 112 | def __len__(self): 113 | """The length of the sequence is the total number of pages.""" 114 | return self._page.paginator.num_pages 115 | 116 | def __iter__(self): 117 | """Iterate over all the endless pages (from first to last).""" 118 | for i in range(len(self)): 119 | yield self[i + 1] 120 | 121 | def __str__(self): 122 | """Return a rendered Digg-style pagination (by default). 123 | 124 | The callable *settings.PAGE_LIST_CALLABLE* can be used to customize 125 | how the pages are displayed. The callable takes the current page number 126 | and the total number of pages, and must return a sequence of page 127 | numbers that will be displayed. The sequence can contain other values: 128 | 129 | - *'previous'*: will display the previous page in that position; 130 | - *'next'*: will display the next page in that position; 131 | - *'first'*: will display the first page as an arrow; 132 | - *'last'*: will display the last page as an arrow; 133 | - *None*: a separator will be displayed in that position. 134 | 135 | Here is an example of custom calable that displays the previous page, 136 | then the first page, then a separator, then the current page, and 137 | finally the last page:: 138 | 139 | def get_page_numbers(current_page, num_pages): 140 | return ('previous', 1, None, current_page, 'last') 141 | 142 | If *settings.PAGE_LIST_CALLABLE* is None an internal callable is used, 143 | generating a Digg-style pagination. The value of 144 | *settings.PAGE_LIST_CALLABLE* can also be a dotted path to a callable. 145 | """ 146 | if len(self) > 1: 147 | pages_callable = utils.get_page_numbers 148 | pages = [] 149 | for item in pages_callable(self._page.number, len(self)): 150 | if item is None: 151 | pages.append(None) 152 | elif item == 'previous': 153 | pages.append(self.previous()) 154 | elif item == 'next': 155 | pages.append(self.next()) 156 | elif item == 'first': 157 | pages.append(self.first_as_arrow()) 158 | elif item == 'last': 159 | pages.append(self.last_as_arrow()) 160 | else: 161 | pages.append(self[item]) 162 | return loader.render_to_string('simple/show_pages.html', {'pages': pages}) 163 | return '' 164 | 165 | def current(self): 166 | """Return the current page.""" 167 | return self._endless_page(self._page.number) 168 | 169 | def current_start_index(self): 170 | """Return the 1-based index of the first item on the current page.""" 171 | return self._page.start_index() 172 | 173 | def current_end_index(self): 174 | """Return the 1-based index of the last item on the current page.""" 175 | return self._page.end_index() 176 | 177 | def total_count(self): 178 | """Return the total number of objects, across all pages.""" 179 | return self._page.paginator.count 180 | 181 | def first(self, label=None): 182 | """Return the first page.""" 183 | return self._endless_page(1, label=label) 184 | 185 | def last(self, label=None): 186 | """Return the last page.""" 187 | return self._endless_page(len(self), label=label) 188 | 189 | def first_as_arrow(self): 190 | """Return the first page as an arrow. 191 | 192 | The page label (arrow) is defined in ``settings.FIRST_LABEL``. 193 | """ 194 | return self.first(label=settings.FIRST_LABEL) 195 | 196 | def last_as_arrow(self): 197 | """Return the last page as an arrow. 198 | 199 | The page label (arrow) is defined in ``settings.LAST_LABEL``. 200 | """ 201 | return self.last(label=settings.LAST_LABEL) 202 | 203 | def previous(self): 204 | """Return the previous page. 205 | 206 | The page label is defined in ``settings.PREVIOUS_LABEL``. 207 | Return an empty string if current page is the first. 208 | """ 209 | if self._page.has_previous(): 210 | return self._endless_page( 211 | self._page.previous_page_number(), 212 | label=settings.PREVIOUS_LABEL) 213 | return '' 214 | 215 | def next(self): 216 | """Return the next page. 217 | 218 | The page label is defined in ``settings.NEXT_LABEL``. 219 | Return an empty string if current page is the last. 220 | """ 221 | if self._page.has_next(): 222 | return self._endless_page( 223 | self._page.next_page_number(), 224 | label=settings.NEXT_LABEL) 225 | return '' 226 | 227 | def paginated(self): 228 | """Return True if this page list contains more than one page.""" 229 | return len(self) > 1 230 | 231 | 232 | class ShowItems(): 233 | """A page link representation. 234 | 235 | Interesting attributes: 236 | 237 | - *self.number*: the page number; 238 | - *self.label*: the label of the link 239 | (usually the page number as string); 240 | - *self.url*: the url of the page (starting with "?"); 241 | - *self.path*: the path of the page; 242 | - *self.is_current*: return True if page is the current page displayed; 243 | - *self.is_first*: return True if page is the first page; 244 | - *self.is_last*: return True if page is the last page. 245 | """ 246 | 247 | def __init__(self, request, page, querystring_key, **kwargs): 248 | default_number = kwargs.get('default_number', None) 249 | override_path = kwargs.get('override_path', None) 250 | self._request = request 251 | self._page = page 252 | if default_number is None: 253 | self._default_number = 1 254 | else: 255 | self._default_number = int(default_number) 256 | self._querystring_key = querystring_key 257 | self._override_path = override_path 258 | 259 | def __str__(self): 260 | """Render the page as a link.""" 261 | str_data = "Showing " 262 | if self._page.paginator.count == 1: 263 | str_data += str(1) 264 | str_data = str_data + " to " + str(len(self._page.object_list)) + " of " + str(len(self._page.object_list)) 265 | else: 266 | if self._page.number == 1: 267 | str_data += str(1) 268 | if self._page.paginator.per_page == str(self._page.paginator.count): 269 | str_data = str_data + " to " + str(self._page.paginator.per_page) + " of " + str(self._page.paginator.count) 270 | else: 271 | str_data = str_data + " to " + str(len(self._page.object_list)) + " of " + str(self._page.paginator.count) 272 | else: 273 | if self._page.has_next(): 274 | str_data += "".join(map(str, [ 275 | (self._page.paginator.per_page * self._page.previous_page_number()) + 1, 276 | " to ", 277 | self._page.paginator.per_page * self._page.number, 278 | " of ", 279 | self._page.paginator.count 280 | ])) 281 | else: 282 | str_data += "".join(map(str, [ 283 | self._page.paginator.per_page * self._page.previous_page_number() + 1, 284 | " to ", 285 | self._page.paginator.count, 286 | " of ", 287 | self._page.paginator.count 288 | ])) 289 | 290 | return str_data + " items" 291 | -------------------------------------------------------------------------------- /simple_pagination/settings.py: -------------------------------------------------------------------------------- 1 | from django.conf import settings 2 | 3 | PER_PAGE = getattr(settings, 'SIMPLE_PAGINATION_PER_PAGE', 10) 4 | PAGE_LABEL = getattr(settings, 'SIMPLE_PAGINATION_PAGE_LABEL', 'page') 5 | NEXT_LABEL = getattr( 6 | settings, 'SIMPLE_PAGINATION_NEXT_LABEL', '') 7 | PREVIOUS_LABEL = getattr( 8 | settings, 'SIMPLE_PAGINATION_PREVIOUS_LABEL', '') 9 | LAST_LABEL = getattr( 10 | settings, 'SIMPLE_PAGINATION_LAST_LABEL', '') 11 | FIRST_LABEL = getattr( 12 | settings, 'SIMPLE_PAGINATION_FIRST_LABEL', '') 13 | -------------------------------------------------------------------------------- /simple_pagination/templates/simple/current_link.html: -------------------------------------------------------------------------------- 1 |
  • {{ page.label|safe }}
  • -------------------------------------------------------------------------------- /simple_pagination/templates/simple/page_link.html: -------------------------------------------------------------------------------- 1 |
  • {{ page.label|safe }}
  • -------------------------------------------------------------------------------- /simple_pagination/templates/simple/show_pages.html: -------------------------------------------------------------------------------- 1 |
      2 | {% for page in pages %}{{page}}{% endfor %} 3 |
    4 | -------------------------------------------------------------------------------- /simple_pagination/templatetags/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MicroPyramid/django-simple-pagination/dce9941df940d864c0533d732adb2602e4045209/simple_pagination/templatetags/__init__.py -------------------------------------------------------------------------------- /simple_pagination/templatetags/paginate.py: -------------------------------------------------------------------------------- 1 | """Django Endless Pagination template tags.""" 2 | 3 | import re 4 | 5 | from django import template 6 | from simple_pagination import settings 7 | from django.core.paginator import ( 8 | EmptyPage, 9 | Paginator, 10 | ) 11 | from simple_pagination import utils 12 | from simple_pagination import models 13 | 14 | 15 | PAGINATE_EXPRESSION = re.compile(r""" 16 | ^ # Beginning of line. 17 | (((?P\w+)\,)?(?P\w+)\s+)? # First page, per page. 18 | (?P[\.\w]+) # Objects / queryset. 19 | (\s+starting\s+from\s+page\s+(?P[\-]?\d+|\w+))? # Page start. 20 | (\s+using\s+(?P[\"\'\-\w]+))? # Querystring key. 21 | (\s+with\s+(?P[\"\'\/\w]+))? # Override path. 22 | (\s+as\s+(?P\w+))? # Context variable name. 23 | $ # End of line. 24 | """, re.VERBOSE) 25 | SHOW_CURRENT_NUMBER_EXPRESSION = re.compile(r""" 26 | ^ # Beginning of line. 27 | (starting\s+from\s+page\s+(?P\w+))?\s* # Page start. 28 | (using\s+(?P[\"\'\-\w]+))?\s* # Querystring key. 29 | (as\s+(?P\w+))? # Context variable name. 30 | $ # End of line. 31 | """, re.VERBOSE) 32 | 33 | 34 | register = template.Library() 35 | 36 | 37 | @register.tag 38 | def paginate(_, token, paginator_class=None): 39 | """Paginate objects. 40 | 41 | Usage: 42 | 43 | .. code-block:: html+django 44 | 45 | {% paginate entries %} 46 | 47 | After this call, the *entries* variable in the template context is replaced 48 | by only the entries of the current page. 49 | 50 | You can also keep your *entries* original variable (usually a queryset) 51 | and add to the context another name that refers to entries of the current 52 | page, e.g.: 53 | 54 | .. code-block:: html+django 55 | 56 | {% paginate entries as page_entries %} 57 | 58 | The *as* argument is also useful when a nested context variable is provided 59 | as queryset. In this case, and only in this case, the resulting variable 60 | name is mandatory, e.g.: 61 | 62 | .. code-block:: html+django 63 | 64 | {% paginate entries.all as entries %} 65 | 66 | The number of paginated entries is taken from settings, but you can 67 | override the default locally, e.g.: 68 | 69 | .. code-block:: html+django 70 | 71 | {% paginate 20 entries %} 72 | 73 | Of course you can mix it all: 74 | 75 | .. code-block:: html+django 76 | 77 | {% paginate 20 entries as paginated_entries %} 78 | 79 | By default, the first page is displayed the first time you load the page, 80 | but you can change this, e.g.: 81 | 82 | .. code-block:: html+django 83 | 84 | {% paginate entries starting from page 3 %} 85 | 86 | When changing the default page, it is also possible to reference the last 87 | page (or the second last page, and so on) by using negative indexes, e.g: 88 | 89 | .. code-block:: html+django 90 | 91 | {% paginate entries starting from page -1 %} 92 | 93 | This can be also achieved using a template variable that was passed to the 94 | context, e.g.: 95 | 96 | .. code-block:: html+django 97 | 98 | {% paginate entries starting from page page_number %} 99 | 100 | If the passed page number does not exist, the first page is displayed. 101 | 102 | If you have multiple paginations in the same page, you can change the 103 | querydict key for the single pagination, e.g.: 104 | 105 | .. code-block:: html+django 106 | 107 | {% paginate entries using article_page %} 108 | 109 | In this case *article_page* is intended to be a context variable, but you 110 | can hardcode the key using quotes, e.g.: 111 | 112 | .. code-block:: html+django 113 | 114 | {% paginate entries using 'articles_at_page' %} 115 | 116 | Again, you can mix it all (the order of arguments is important): 117 | 118 | .. code-block:: html+django 119 | 120 | {% paginate 20 entries 121 | starting from page 3 using page_key as paginated_entries %} 122 | 123 | Additionally you can pass a path to be used for the pagination: 124 | 125 | .. code-block:: html+django 126 | 127 | {% paginate 20 entries 128 | using page_key with pagination_url as paginated_entries %} 129 | 130 | This way you can easily create views acting as API endpoints, and point 131 | your Ajax calls to that API. In this case *pagination_url* is considered a 132 | context variable, but it is also possible to hardcode the URL, e.g.: 133 | 134 | .. code-block:: html+django 135 | 136 | {% paginate 20 entries with "/mypage/" %} 137 | 138 | If you want the first page to contain a different number of items than 139 | subsequent pages, you can separate the two values with a comma, e.g. if 140 | you want 3 items on the first page and 10 on other pages: 141 | 142 | .. code-block:: html+django 143 | 144 | {% paginate 3,10 entries %} 145 | 146 | You must use this tag before calling the {% show_more %} one. 147 | """ 148 | # Validate arguments. 149 | try: 150 | tag_name, tag_args = token.contents.split(None, 1) 151 | except ValueError: 152 | msg = '%r tag requires arguments' % token.contents.split()[0] 153 | raise template.TemplateSyntaxError(msg) 154 | 155 | # Use a regexp to catch args. 156 | match = PAGINATE_EXPRESSION.match(tag_args) 157 | if match is None: 158 | msg = 'Invalid arguments for %r tag' % tag_name 159 | raise template.TemplateSyntaxError(msg) 160 | 161 | # Retrieve objects. 162 | kwargs = match.groupdict() 163 | objects = kwargs.pop('objects') 164 | 165 | # The variable name must be present if a nested context variable is passed. 166 | if '.' in objects and kwargs['var_name'] is None: 167 | msg = ( 168 | '%(tag)r tag requires a variable name `as` argumnent if the ' 169 | 'queryset is provided as a nested context variable (%(objects)s). ' 170 | 'You must either pass a direct queryset (e.g. taking advantage ' 171 | 'of the `with` template tag) or provide a new variable name to ' 172 | 'store the resulting queryset (e.g. `%(tag)s %(objects)s as ' 173 | 'objects`).' 174 | ) % {'tag': tag_name, 'objects': objects} 175 | raise template.TemplateSyntaxError(msg) 176 | 177 | # Call the node. 178 | return PaginateNode(paginator_class, objects, **kwargs) 179 | 180 | 181 | class PaginateNode(template.Node): 182 | """Add to context the objects of the current page. 183 | 184 | Also add the Django paginator's *page* object. 185 | """ 186 | 187 | def __init__(self, paginator_class, objects, **kwargs): 188 | first_page = kwargs.get('first_page', None) 189 | per_page = kwargs.get('per_page', None) 190 | var_name = kwargs.get('var_name', None) 191 | number = kwargs.get('number', None) 192 | key = kwargs.get('key', None) 193 | override_path = kwargs.get('override_path', None) 194 | self.paginator = paginator_class or Paginator 195 | self.objects = template.Variable(objects) 196 | 197 | # If *var_name* is not passed, then the queryset name will be used. 198 | self.var_name = objects if var_name is None else var_name 199 | 200 | # If *per_page* is not passed then the default value from settings 201 | # will be used. 202 | self.per_page_variable = None 203 | if per_page is None: 204 | self.per_page = settings.PER_PAGE 205 | elif per_page.isdigit(): 206 | self.per_page = int(per_page) 207 | else: 208 | self.per_page_variable = template.Variable(per_page) 209 | 210 | # Handle first page: if it is not passed then *per_page* is used. 211 | self.first_page_variable = None 212 | if first_page is None: 213 | self.first_page = None 214 | elif first_page.isdigit(): 215 | self.first_page = int(first_page) 216 | else: 217 | self.first_page_variable = template.Variable(first_page) 218 | 219 | # Handle page number when it is not specified in querystring. 220 | self.page_number_variable = None 221 | if number is None: 222 | self.page_number = 1 223 | else: 224 | try: 225 | self.page_number = int(number) 226 | except ValueError: 227 | self.page_number_variable = template.Variable(number) 228 | 229 | # Set the querystring key attribute. 230 | self.querystring_key_variable = None 231 | if key is None: 232 | self.querystring_key = settings.PAGE_LABEL 233 | elif key[0] in ('"', "'") and key[-1] == key[0]: 234 | self.querystring_key = key[1:-1] 235 | else: 236 | self.querystring_key_variable = template.Variable(key) 237 | 238 | # Handle *override_path*. 239 | self.override_path_variable = None 240 | if override_path is None: 241 | self.override_path = None 242 | elif ( 243 | override_path[0] in ('"', "'") and 244 | override_path[-1] == override_path[0]): 245 | self.override_path = override_path[1:-1] 246 | else: 247 | self.override_path_variable = template.Variable(override_path) 248 | 249 | def render(self, context): 250 | # Handle page number when it is not specified in querystring. 251 | if self.page_number_variable is None: 252 | default_number = self.page_number 253 | else: 254 | default_number = int(self.page_number_variable.resolve(context)) 255 | 256 | # Calculate the number of items to show on each page. 257 | if self.per_page_variable is None: 258 | per_page = self.per_page 259 | else: 260 | per_page = int(self.per_page_variable.resolve(context)) 261 | 262 | # User can override the querystring key to use in the template. 263 | # The default value is defined in the settings file. 264 | if self.querystring_key_variable is None: 265 | querystring_key = self.querystring_key 266 | else: 267 | querystring_key = self.querystring_key_variable.resolve(context) 268 | 269 | # Retrieve the override path if used. 270 | if self.override_path_variable is None: 271 | override_path = self.override_path 272 | else: 273 | override_path = self.override_path_variable.resolve(context) 274 | 275 | # Retrieve the queryset and create the paginator object. 276 | objects = self.objects.resolve(context) 277 | paginator = self.paginator( 278 | objects, per_page) 279 | 280 | # Normalize the default page number if a negative one is provided. 281 | if default_number < 0: 282 | default_number = utils.normalize_page_number( 283 | default_number, paginator.page_range) 284 | 285 | # The current request is used to get the requested page number. 286 | page_number = utils.get_page_number_from_request( 287 | context['request'], querystring_key, default=default_number) 288 | 289 | # Get the page. 290 | try: 291 | page = paginator.page(page_number) 292 | except EmptyPage: 293 | page = paginator.page(1) 294 | 295 | # Populate the context with required data. 296 | data = { 297 | 'default_number': default_number, 298 | 'override_path': override_path, 299 | 'page': page, 300 | 'querystring_key': querystring_key, 301 | } 302 | context.update({'endless': data, self.var_name: page.object_list}) 303 | return '' 304 | 305 | 306 | @register.tag 307 | def show_pages(_, token): 308 | """Show page links. 309 | 310 | Usage: 311 | 312 | .. code-block:: html+django 313 | 314 | {% show_pages %} 315 | 316 | It is just a shortcut for: 317 | 318 | .. code-block:: html+django 319 | 320 | {% get_pages %} 321 | {{ pages }} 322 | 323 | You can set ``ENDLESS_PAGINATION_PAGE_LIST_CALLABLE`` in your *settings.py* 324 | to a callable, or to a dotted path representing a callable, used to 325 | customize the pages that are displayed. 326 | 327 | See the *__unicode__* method of ``endless_pagination.models.PageList`` for 328 | a detailed explanation of how the callable can be used. 329 | 330 | Must be called after ``{% paginate objects %}``. 331 | """ 332 | # Validate args. 333 | if len(token.contents.split()) != 1: 334 | msg = '%r tag takes no arguments' % token.contents.split()[0] 335 | raise template.TemplateSyntaxError(msg) 336 | # Call the node. 337 | return ShowPagesNode() 338 | 339 | 340 | class ShowPagesNode(template.Node): 341 | """Show the pagination.""" 342 | 343 | def render(self, context): 344 | # This template tag could raise a PaginationError: you have to call 345 | # *paginate* or *lazy_paginate* before including the getpages template. 346 | data = utils.get_data_from_context(context) 347 | # Return the string representation of the sequence of pages. 348 | pages = models.PageList( 349 | context['request'], 350 | data['page'], 351 | data['querystring_key'], 352 | default_number=data['default_number'], 353 | override_path=data['override_path'], 354 | ) 355 | return str(pages) 356 | 357 | 358 | @register.tag 359 | def show_pageitems(_, token): 360 | """Show page items. 361 | 362 | Usage: 363 | 364 | .. code-block:: html+django 365 | 366 | {% show_pageitems per_page %} 367 | 368 | """ 369 | # Validate args. 370 | if len(token.contents.split()) != 1: 371 | msg = '%r tag takes no arguments' % token.contents.split()[0] 372 | raise template.TemplateSyntaxError(msg) 373 | # Call the node. 374 | return ShowPageItemsNode() 375 | 376 | 377 | class ShowPageItemsNode(template.Node): 378 | """Show the pagination.""" 379 | 380 | def render(self, context): 381 | # This template tag could raise a PaginationError: you have to call 382 | # *paginate* or *lazy_paginate* before including the getpages template. 383 | data = utils.get_data_from_context(context) 384 | pages = models.ShowItems( 385 | context['request'], 386 | data['page'], 387 | data['querystring_key'], 388 | default_number=data['default_number'], 389 | override_path=data['override_path'], 390 | ) 391 | return str(pages) 392 | -------------------------------------------------------------------------------- /simple_pagination/tests.py: -------------------------------------------------------------------------------- 1 | from django.test import TestCase 2 | from django.template import Template, Context 3 | from django.http import HttpRequest 4 | from simple_pagination.utils import( 5 | normalize_page_number, 6 | get_querystring_for_page, 7 | get_page_numbers, 8 | ) 9 | from simple_pagination.models import EndlessPage, PageList, ShowItems 10 | from django.http import QueryDict 11 | from django.core.paginator import Paginator 12 | 13 | 14 | class PaginateAndShowPageItems(TestCase): 15 | 16 | def test_addition(self): 17 | t = Template( 18 | "{% load paginate %}{% paginate entities %}.{% show_pageitems %} {% paginate 20 entities %} {% show_pages %}") 19 | req = HttpRequest() 20 | c = Context({"entities": range(100), 'request': req}) 21 | val = t.render(c) 22 | self.assertTrue(bool(val)) 23 | 24 | 25 | class NormalizePageNumber(TestCase): 26 | 27 | def test_normalize_page_number(self): 28 | page_number = 1 29 | page_range = range(2) 30 | val = normalize_page_number(page_number, page_range) 31 | self.assertTrue(bool(val)) 32 | page_range = range(1) 33 | val = normalize_page_number(page_number, page_range) 34 | self.assertFalse(bool(val)) 35 | 36 | 37 | class GetQuerystringForPage(TestCase): 38 | 39 | def test_get_querystring_for_page(self): 40 | request = self 41 | request = HttpRequest() 42 | dict = {u"querystring_key": 1, 43 | u"key": 2, 44 | u"page": 3} 45 | qdict = QueryDict('', mutable=True) 46 | qdict.update(dict) 47 | request.GET = qdict 48 | val = get_querystring_for_page(request=request, 49 | page_number=1, 50 | querystring_key="key", 51 | default_number=1) 52 | self.assertTrue(bool(val)) 53 | request.GET = {} 54 | val = get_querystring_for_page(request=request, 55 | page_number=1, 56 | querystring_key="key", 57 | default_number=1) 58 | self.assertFalse(bool(val)) 59 | 60 | 61 | class GetPageNumbers(TestCase): 62 | 63 | def test_get_page_numbers(self): 64 | self.assertTrue(get_page_numbers(current_page=2, num_pages=10)) 65 | self.assertTrue(get_page_numbers(current_page=9, num_pages=10)) 66 | self.assertTrue(get_page_numbers(current_page=1, num_pages=3)) 67 | 68 | 69 | class TestEndlessPage(TestCase): 70 | 71 | def test_endless_page(self): 72 | request = HttpRequest() 73 | epage = EndlessPage(request=request, 74 | number=2, 75 | current_number=2, 76 | total_number=10, 77 | querystring_key='page') 78 | self.assertTrue(epage) 79 | 80 | 81 | class TestPageList(TestCase): 82 | 83 | def test_page_list(self): 84 | request = HttpRequest() 85 | paginator = Paginator(['john', 'paul', 'george', 'ringo'], 3) 86 | page = paginator.page(1) 87 | page.number = lambda: None 88 | setattr(page, 'number', 2) 89 | setattr(page, 'paginator', paginator) 90 | page_list = PageList(request=request, page=page, querystring_key="page") 91 | page_list = PageList(request=request, page=page, querystring_key="page", default_number=1) 92 | page_list._endless_page(number=1) 93 | page_list._endless_page(number=3) 94 | self.assertTrue(page_list[1]) 95 | page_list.next() 96 | self.assertTrue(page_list) 97 | si = ShowItems(request=request, page=page, querystring_key="page") 98 | self.assertTrue(si) 99 | -------------------------------------------------------------------------------- /simple_pagination/utils.py: -------------------------------------------------------------------------------- 1 | from __future__ import unicode_literals 2 | import urllib 3 | 4 | from simple_pagination.settings import ( 5 | PAGE_LABEL 6 | ) 7 | 8 | 9 | def get_data_from_context(context): 10 | """Get the django paginator data object from the given *context*. 11 | The context is a dict-like object. If the context key ``endless`` 12 | is not found, a *PaginationError* is raised. 13 | """ 14 | try: 15 | return context['endless'] 16 | except KeyError: 17 | raise Exception('Cannot find endless data in context.') 18 | 19 | 20 | def get_page_number_from_request( 21 | request, querystring_key=PAGE_LABEL, default=1): 22 | """Retrieve the current page number from *GET* or *POST* data. 23 | If the page does not exists in *request*, or is not a number, 24 | then *default* number is returned. 25 | """ 26 | try: 27 | return int(request.GET[querystring_key]) 28 | except (KeyError, TypeError, ValueError): 29 | return default 30 | 31 | 32 | def get_page_numbers(current_page, num_pages): 33 | """Default callable for page listing. 34 | Produce a Digg-style pagination. 35 | """ 36 | 37 | if current_page <= 2: 38 | start_page = 1 39 | else: 40 | start_page = current_page - 2 41 | 42 | if num_pages <= 4: 43 | end_page = num_pages 44 | else: 45 | end_page = start_page + 4 46 | if end_page > num_pages: 47 | end_page = num_pages 48 | 49 | pages = [] 50 | if current_page != 1: 51 | pages.append('first') 52 | pages.append('previous') 53 | pages.extend([i for i in range(start_page, end_page + 1)]) 54 | if current_page != num_pages: 55 | pages.append('next') 56 | pages.append('last') 57 | return pages 58 | 59 | 60 | def get_querystring_for_page( 61 | request, page_number, querystring_key, default_number=1): 62 | """Return a querystring pointing to *page_number*.""" 63 | querydict = request.GET.copy() 64 | querydict[querystring_key] = page_number 65 | # For the default page number (usually 1) the querystring is not required. 66 | if page_number == default_number: 67 | del querydict[querystring_key] 68 | if 'querystring_key' in querydict: 69 | del querydict['querystring_key'] 70 | if querydict: 71 | return '?' + urllib.parse.urlencode(querydict) 72 | return '' 73 | 74 | 75 | def normalize_page_number(page_number, page_range): 76 | """Handle a negative *page_number*. 77 | Return a positive page number contained in *page_range*. 78 | If the negative index is out of range, return the page number 1. 79 | """ 80 | try: 81 | return page_range[page_number] 82 | except IndexError: 83 | return page_range[0] 84 | -------------------------------------------------------------------------------- /test_runner.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import os 3 | import sys 4 | 5 | import django 6 | from django.conf import settings 7 | from django.test.utils import get_runner 8 | 9 | if __name__ == "__main__": 10 | settings.configure( 11 | DATABASES={ 12 | 'default': { 13 | 'ENGINE': 'django.db.backends.sqlite3', 14 | } 15 | }, 16 | INSTALLED_APPS=('simple_pagination',), 17 | TEMPLATES=[ 18 | { 19 | 'BACKEND': 'django.template.backends.django.DjangoTemplates', 20 | 'DIRS': [], 21 | 'APP_DIRS': True, 22 | 'OPTIONS': { 23 | 'context_processors': [ 24 | 'django.template.context_processors.debug', 25 | 'django.template.context_processors.request', 26 | 'django.contrib.auth.context_processors.auth', 27 | 'django.contrib.messages.context_processors.messages', 28 | ], 29 | }, 30 | }, 31 | ] 32 | ) 33 | os.environ['DJANGO_SETTINGS_MODULE'] = 'simple_pagination.settings' 34 | django.setup() 35 | TestRunner = get_runner(settings) 36 | test_runner = TestRunner() 37 | failures = test_runner.run_tests(["simple_pagination"]) 38 | sys.exit(bool(failures)) 39 | --------------------------------------------------------------------------------