Giter Site home page Giter Site logo

django-pure-pagination's Introduction

django-pure-pagination

image

Description

Author

James Pacileo @ignighted

Version

0.3.0

Description

django-pure-pagination provides advanced pagination features and is fully compatible with existing code based on Django's core pagination module. (aka no need to rewrite code!)

Requirements

Django 1.7+

Contributors

juandecarrion (Juande Carrion), twidi (Stéphane Angel), bebraw (Juho Vepsäläinen), lampslave (), GeyseR (Sergey Fursov), zeus (Pavel Zhukov)

Introduction

The django app offers advanced pagination features without forcing major code changes within an existing project.

Django-pure-pagination is based upon Django's core pagination module and is therefore compatible with the existing api.

Documentation for Django core pagination module

Features

  1. Uses same API as django.core.pagination and therefore is fully compatible with existing code.
  2. Has dynamic query string creation, which takes into consideration existing GET parameters.
  3. Out-of-the-box html rendering of the pagination
  4. Additional methods make it easier to render more advanced pagination templates.

Installation

Install package from PYPI:

pip install django-pure-pagination

or clone and install from repository:

git clone [email protected]:jamespacileo/django-pure-pagination.git
cd django-pure-pagination
python setup.py install

Add pure_pagination to INSTALLED_APPS

INSTALLED_APPS = (
    ...
    'pure_pagination',
)

Finally substitute from django.core.paginator import Paginator with from pure_pagination import Paginator

Settings

A few settings can be set within settings.py

PAGINATION_SETTINGS = {
    'PAGE_RANGE_DISPLAYED': 10,
    'MARGIN_PAGES_DISPLAYED': 2,

    'SHOW_FIRST_PAGE_WHEN_INVALID': True,
}

PAGE_RANGE_DISPLAYED is the number of pages neighbouring the current page which will be displayed (default is 10)

MARGIN_PAGES_DISPLAYED is the number of pages neighbouring the first and last page which will be displayed (default is 2)

Set SHOW_FIRST_PAGE_WHEN_INVALID to True when you want to just show first page when provided invalid page instead of 404 error

image

Usage example

Following is a simple example for function based views. For generic class-based views, see bellow.

view file: views.py

# views.py
from django.shortcuts import render_to_response

from pure_pagination import Paginator, EmptyPage, PageNotAnInteger


def index(request):

    try:
        page = request.GET.get('page', 1)
    except PageNotAnInteger:
        page = 1

    objects = ['john', 'edward', 'josh', 'frank']

    # Provide Paginator with the request object for complete querystring generation

    p = Paginator(objects, request=request)

    people = p.page(page)

    return render_to_response('index.html', {
        'people': people,
    }

template file: index.html

{# index.html #}
{% extends 'base.html' %}

{% block content %}

{% for person in people.object_list %}
    <div>
        First name: {{ person }}
    </div>
{% endfor %}

{# The following renders the pagination html #}
<div id="pagination">
    {{ people.render }}
</div>

{% endblock %}

Usage

There a few different way you can make use of the features introduced within django-pure-pagination.

Easiest way to render the pagination is to call the render method i.e. {{ page.render }}

Alternatively you can access the Page object low level methods yourself

Special note: page_obj and current_page both point to the page object within the template.

{% load i18n %}
<div class="pagination">
    {% if page_obj.has_previous %}
        <a href="?{{ page_obj.previous_page_number.querystring }}" class="prev">&lsaquo;&lsaquo; {% trans "previous" %}</a>
    {% else %}
        <span class="disabled prev">&lsaquo;&lsaquo; {% trans "previous" %}</span>
    {% endif %}
    {% for page in page_obj.pages %}
        {% if page %}
            {% ifequal page page_obj.number %}
                <span class="current page">{{ page }}</span>
            {% else %}
                <a href="?{{ page.querystring }}" class="page">{{ page }}</a>
            {% endifequal %}
        {% else %}
            ...
        {% endif %}
    {% endfor %}
    {% if page_obj.has_next %}
        <a href="?{{ page_obj.next_page_number.querystring }}" class="next">{% trans "next" %} &rsaquo;&rsaquo;</a>
    {% else %}
        <span class="disabled next">{% trans "next" %} &rsaquo;&rsaquo;</span>
    {% endif %}
</div>

Generic Class-Based Views

Documentation for Django generic class-based views on https://docs.djangoproject.com/en/dev/ref/class-based-views/

view file:

  • views.py

    # views.py
    from django.views.generic import ListView
    
    from pure_pagination.mixins import PaginationMixin
    
    from my_app.models import MyModel
    
    
    class MyModelListView(PaginationMixin, ListView):
        # Important, this tells the ListView class we are paginating
        paginate_by = 10
    
        # Replace it for your model or use the queryset attribute instead
        object = MyModel

template files:

Note that the Django generic-based list view will include the object page_obj in the context. More information on https://docs.djangoproject.com/en/dev/ref/generic-views/#list-detail-generic-views

  • _pagination.html

    {% load i18n %}
    <div class="pagination">
        {% if page_obj.has_previous %}
            <a href="?{{ page_obj.previous_page_number.querystring }}" class="prev">&lsaquo;&lsaquo; {% trans "previous" %}</a>
        {% else %}
            <span class="disabled prev">&lsaquo;&lsaquo; {% trans "previous" %}</span>
        {% endif %}
        {% for page in page_obj.pages %}
            {% if page %}
                {% ifequal page page_obj.number %}
                    <span class="current page">{{ page }}</span>
                {% else %}
                    <a href="?{{ page.querystring }}" class="page">{{ page }}</a>
                {% endifequal %}
            {% else %}
                ...
            {% endif %}
        {% endfor %}
        {% if page_obj.has_next %}
            <a href="?{{ page_obj.next_page_number.querystring }}" class="next">{% trans "next" %} &rsaquo;&rsaquo;</a>
        {% else %}
            <span class="disabled next">{% trans "next" %} &rsaquo;&rsaquo;</span>
        {% endif %}
    </div>
  • my_app/myobject_list.html

    {# my_app/myobject_list.html #}
    {% extends 'base.html' %}
    
    {% block content %}
    
    {% for object in object_list %}
        <div>
            First name: {{ object.first_name }}
        </div>
    {% endfor %}
    
    {# The following renders the pagination html #}
    {% include "_pagination.html" %}
    
    {% endblock %}

django-pure-pagination's People

Contributors

asfaltboy avatar darkjaguar avatar flaviusim avatar geyser avatar gmixo avatar juandecarrion avatar lampslave avatar twidi avatar zeus avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

django-pure-pagination's Issues

'int' object has no attribute 'encode'

when using this useful plugin, something happens:
Bellow are the messages from pycharm.
`
File "E:\work\python\FollowUpSystem_H5_new\web\views.py", line 439, in get
patient_set_paged = p.page(page)
File "E:\work\python\env\FollowUpSystem\lib\site-packages\pure_pagination\paginator.py", line 54, in page
return Page(self.object_list[bottom:top], number, self)
File "E:\work\python\env\FollowUpSystem\lib\site-packages\pure_pagination\paginator.py", line 129, in init
self.number = PageRepresentation(number, self.other_page_querystring(number))
File "E:\work\python\env\FollowUpSystem\lib\site-packages\pure_pagination\paginator.py", line 206, in other_page_querystring
return self.base_queryset.urlencode()
File "E:\work\python\env\FollowUpSystem\lib\site-packages\django\http\request.py", line 524, in urlencode
for v in list

File "E:\work\python\env\FollowUpSystem\lib\site-packages\django\http\request.py", line 524, in
for v in list

AttributeError: 'int' object has no attribute 'encode'

**my codes**
try:
page = request.GET.get('page', 1)
except PageNotAnInteger:
page = 1
p = Paginator(object_list=patient_set, per_page=10, request=request)
patient_set_paged = p.page(page)

        return render(request, "patient_list.html", {

`
i will be very happy if i can get your help

http://www.syrme.top/list/1.html?page=2?visitDstTime=1

But when it works on the server, it comes up with this

def fen(request,contact_list):
	try:
		page = request.GET.get('page', 1)
	except PageNotAnInteger:
		page = 1
	p = Paginator(contact_list, 30)
	contact_list = p.page(page)
	return contact_list


def movie(request, head_id):
	context_mv = Movie.objects.filter(movie_head=head_id)[::-1]
	number = len(context_mv)
	context = fen(request, context_mv)
	return render(request, 'movie/more.html', {'context': context, 'number': number})

readme bug

Hi :) Please, fix readme:

def index(request):
    objects = ['john', 'edward', 'josh', 'frank']
    p = Paginator(objects, request=request)
    try:
        people = p.page(request.GET.get('page', 1))
    except (EmptyPage, PageNotAnInteger):
        raise Http404
    return render_to_response('index.html', {
        'people': people,
    })

In python3.6 and Django2.1 error

File "xxx\views.py", line 25, in get
all_article = p.page(page)

AttributeError: 'int' object has no attribute 'encode'

        try:
            page = request.GET.get('page', 1)
        except PageNotAnInteger:
            page = 1

        p = Paginator(all_article, per_page=5, request=request)  # 每页显示5条

        all_article = p.page(page)

Readme error

Hi,
Readme Usage example says:
p = Paginator(objects, request=request)
Actually I meet excption and check your code, here need a page_size after objects for objects per page.
``p = Paginator(objects, per_page=6, request=request)`

ubuntu14.04 not install

ubuntu14.04 error 0855970a5ce02ea12f5a53d520315f200b4847a1/django-pure-pagination-0.3.0.tar.gz
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "", line 1, in
File "/tmp/pip-install-isuua6j4/django-pure-pagination/setup.py", line 5, in
README = readme.read()
File "/var/env/django_env/lib/python3.4/encodings/ascii.py", line 26, in decode
return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 672: ordinal not in range(128)

----------------------------------------

Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-install-isuua6j4/django-pure-pagination/
(django_env) root@iZ941w016mwZ:~#

sample code causes exception

Code the in usage example (in views.py) says Paginator accepts the request object as a parameter. This causes an__init__() takes 3 arguments exception. After checking the source it looks like it should be

 p = Paginator(suburb_list, per_page=10)

which is also what ended up working for me.

Additionally the sample code for the Generic Class-Based View sets an object property as the model type, it should set the model property instead. As in

class MyModelListView(PaginationMixin, ListView):
    # Important, this tells the ListView class we are paginating
    paginate_by = 10

    # Replace it for your model or use the queryset attribute instead
    model = MyModel

error installing on ubuntu 18.04

 Downloading django-pure-pagination-0.3.0.tar.gz (10 kB)
    ERROR: Command errored out with exit status 1:
     command: /opt/mayan-edms/bin/python3 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-zh_8icc8/django-pure-pagination/setup.py'"'"'; __file__='"'"'/tmp/pip-install-zh_8icc8/django-pure-pagination/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-install-zh_8icc8/django-pure-pagination/pip-egg-info
         cwd: /tmp/pip-install-zh_8icc8/django-pure-pagination/
    Complete output (7 lines):
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/tmp/pip-install-zh_8icc8/django-pure-pagination/setup.py", line 5, in <module>
        README = readme.read()
      File "/opt/mayan-edms/lib/python3.6/encodings/ascii.py", line 26, in decode
        return codecs.ascii_decode(input, self.errors)[0]
    UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 672: ordinal not in range(128)
    ----------------------------------------
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.

This is from PIP install on the latest version of PIP

ValueError with invalid GET parameter

It seems if you provide invalid GET parameters to the app (ie. ?ä), it will fail with some kind of ValueError (ValueError: unsupported format character 'C' (0x43) at index 1). It seems "return self.base_queryset %page_number" at paginator.py is the offending line. I think the bug has something to with the way you deal with base_queryset (copy + page hackery). It would be great if you could look into this.

Give back the maintainer right

Hi,

This repository seems to lack maintenance, I propose myself as a new maintainer.

Could you give me the right to push in your repository or just transfer it on my account in github?

Thank you

Handling of escaped single quotes followed by 's'

If a query with a single quote followed by an s comes in, it is converted to %27s

In line 202, this throws a TypeError because the %27s is interpreted as string formatting. If you change this to the new string formatting using .format() this should not be an issue.

Maintained fork

Hi all, is there any maintained fork out there ?

Thanks !

There is a mistake in the example.

https://github.com/jamespacileo/django-pure-pagination

in this page, "Usage example"

try:
    page = request.GET.get('page', 1)
except PageNotAnInteger:
    page = 1

It's not going to cause an anomaly here.

I think this should be done in the following examples

        page = request.GET.get('page', 1)
        p = Paginator(all_article, 8)

        try:
            all_article_page = p.page(number=page)
        except PageNotAnInteger:
            # page = 1
            all_article_page = p.page(number=1)
        except EmptyPage:
            # page = p.num_pages
            all_article_page = p.page(number=p.num_pages)

Special characters in GET parameters break string interpolation

If one of the GET parameters includes an escaped character (e.g. &) and one passes request into the paginator, _other_page_querystring will break because it's unable to interpolate the page number into the query string:

'query=Spam+%26+Eggs&page=%s' % 1

File "search/views.py", line 25, in search
          results = paginator.page(page)
File "pure_pagination/paginator.py", line 53, in page
          return Page(self.object_list[bottom:top], number, self)
File "pure_pagination/paginator.py", line 126, in __init__
          self.number = PageRepresentation(number, self._other_page_querystring(number))
File "pure_pagination/paginator.py", line 217, in _other_page_querystring
          return self.base_queryset %page_number
ValueError: unsupported format character '+' (0x2b) at index 14

python 3.10 AttributeError: module 'collections' has no attribute 'Iterable'

Got an error when using python 3.10:
I had to do the following change in order to have it back working in my project:

python3.10/site-packages/pure_pagination/paginator.py:
replace the first line "import collections" into:

try: # Python 3.10
    from collections.abc import Iterable
except ImportError:
    from collections import Iterable

AND line 109 " elif isinstance(result, collections.Iterable):" into
elif isinstance(result, Iterable):

Naming of variables in templates

Hi James,

In https://github.com/jamespacileo/django-pure-pagination/blob/master/pure_pagination/templates/pure_pagination/pagination.html the context variable that contains the Current Page Object is called current_page

While in https://docs.djangoproject.com/en/dev/ref/generic-views/#list-detail-generic-views Django uses the name page_obj

Could you change the name of that variable in your code and templates in order to use the same terminology as in Django? A side effect of this would be that the templates in generic class-based list views would be able to include your template instead of forcing the user to rewrite a new template.

If you need more details, let me know.

Sample code may be wrong

p = Paginator(objects, request=request) in views.py may need to add the number of paged pages,
That is modified as p = Paginator(objects, number, request=request)

Otherwise it will report this error: __init__() missing 1 required positional argument: 'per_page'

No margin pages?

Can you turn off margin pages, so it only shows the middle part? Setting MARGIN_PAGES_DISPLAYED to 0 or None doesn't do what I expected...

Also, I seem to be able to get it to work in generic class based views by setting:

paginator_class = Paginator

where Paginator is

from pure_pagination import Paginator. You had mentioned support for generic class based views via a mixin and I was wondering if you were going to do more than just swap out the Pagination class.

Thanks,
Shige

Python 3 compatibility

I was recently using this repository with Python 3.3. I haven't fully tested it, but the only issue I had was with use of "xrange" on line 181 of paginator.py.

One possible way to fix this is adding something like this at the top of the file

# Python 3
try:
    xrange
except(NameError):
    xrange = range

install error

Hi! I get this error when install from pip

$ pip install django-pure-pagination
Collecting django-pure-pagination
Using cached django-pure-pagination-0.3.0.tar.gz
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "", line 1, in
File "/tmp/pip-build-a9onyo91/django-pure-pagination/setup.py", line 5, in
README = readme.read()
File "/home/django/.pyenv/versions/3.5.2/lib/python3.5/encodings/ascii.py", line 26, in decode
return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 672: ordinal not in range(128)
----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-a9onyo91/django-pure-pagination/

Can you assist?
Thanks in advance!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.