Giter VIP home page Giter VIP logo

flask-paginate's Introduction

flask-paginate

Pagination support for flask framework (study from will_paginate). It supports several css frameworks. It requires Python2.6+ as string.format syntax.

If you want to show pagination-info ("Total 100 posts, displaying 20 - 30") above the pagination links, please add the below lines to your css file::

.. sourcecode:: css

.pagination-page-info {
    padding: .6em;
    padding-left: 0;
    width: 40em;
    margin: .5em;
    margin-left: 0;
    font-size: 12px;
}
.pagination-page-info b {
    color: black;
    background: #6aa6ed;
    padding-left: 2px;
    padding: .1em .25em;
    font-size: 150%;
}

Full documentation: http://flask-paginate.readthedocs.io

Run example:

$cd example
$python sql.py
$python sql.py init-db
$python sql.py fill-data --total=310
$cp app.cfg.example app.cfg
$echo edit app.cfg
$python app.py --port 5000

Open http://localhost:5000 to see the example page.

demo

flask-paginate's People

Contributors

alcaras avatar alessandro201 avatar andodet avatar dp92987 avatar dyfeng avatar ilya-il avatar jamesturk avatar jan-janssen avatar lixxu avatar mastermind2k avatar mozillazg avatar mvhconsult avatar n3storm avatar nkubarelov avatar rdbaker avatar skybber avatar stkw0 avatar tark-hidden avatar timgates42 avatar wojkos avatar wong2 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

flask-paginate's Issues

Page links not working

Hi, I'm not sure if this is the right place to ask, but I've been having trouble getting the page links to work. The pagination.links bar shows up, but it's stuck at page 1 when I try selecting the different pages. Thanks in advance!

from flask_wtf import Form
from flask import Flask, render_template, request, redirect, url_for
from wtforms import TextField
from flask_paginate import Pagination, get_page_args

app = Flask(__name__)
app.secret_key = 'abc'

class SearchForm(Form):
    search_term = TextField("Search term")

class DataStore():
    search_term = None

data = DataStore()


@app.route('/')
def index():

    form = SearchForm()
    if form.validate_on_submit():
        data.search_term = form.search_term.data()
        return redirect(url_for('search_results', page = 1))
    return render_template('index.html', form = form)


@app.route('/search/results/', defaults = {'page': 1})
@app.route('/search/results', defaults = {'page': 1})
@app.route('/search/results/<int:page>/')
@app.route('/search/results/<int:page>')
def search_results(page):

    page, per_page, offset = get_page_args()

    # get data based on search form text, assign to res

    pagination = Pagination(page = page, 
                                per_page = per_page, 
                                total = len(res))
    
    return render_template('results.html', res = res, pagination = pagination)

if __name__ == '__main__':
    app.run(host = '127.0.0.1', port = 5000, debug = True)

pagination links are not showing

flask-paginate 0.5.2

my view:

....
        pagination = Pagination(bs_version=3, page=page, total=total, outer_window=0, inner_window=2, )
    context = {
        'banners': banners,
        'boards': boards,
        'posts': posts,
        'pagination': pagination,
        'current_board': board_id
    }
    return render_template('front/front_index.html', **context)

my html template:

           <ul class="post-list-group">
                {% for post in posts %}
                    <li>
                        <div class="author-avatar-group">
                            <img src="{{ post.author.avatar or url_for('static',filename='common/images/logo.png') }}"
                                 alt="">
                        </div>
                        <div class="post-info-group">
                            <p class="post-title">
                                <a href="{{ url_for('front.post_detail',post_id=post.id) }}">{{ post.title }}</a>
                                {% if post.essence %}
                                    <span class="label label-danger">精华帖</span>
                                {% endif %}
                            </p>
                            <p class="post-info">
                                <span>Author:{{ post.author.username }}</span>
                                <span>Post Time:{{ post.create_time }}</span>
                                <span>Comment:0</span>
                                <span>Read:0</span>
                            </p>
                        </div>
                    </li>
                {% endfor %}
            </ul>
            <div style="text-align: center">
                {{ pagination.info }}
                {{ pagination.links}}
            </div>

image

Avoiding to rerun count() each time

Hi, I looked at your example code and you get nice results for the small user example. It is quick for each page in the pagination to rerun g.cur.execute('select count(*) from users'), but if the database is big then it will take a while to rerun the count(*) each time.

How is possible to avoid to rerun count(*) for each page in pagination to do g.cur.execute('select count(*) from users')?

Thank you in advance.

Mic

flask.ext.* is deprecated; use flask_* instead

as the title says - the flask.ext import proxy is deprecated and new code should use the actual package name (flask_paginate) instead; so updating the examples would be a good idea.

TypeError: unsupported operand type(s) for divmod(): 'unicode' and 'int'

I'm trying to implement pagination on sqlite query results but i'm getting the error below. When i use the example given in flask-paginate everything works fine but i trying to simulate a full text search so i'm using UNION in my query and everything seems to work in command line but when i do this in flask flask-paginate returns an exception.

What am i doing wrong?

Traceback (most recent call last):
  File "C:\Users\mundia\OneDrive\101Python\popFlaskPaginate\popFlaskPaginate\venv\lib\site-packages\flask\app.py", line 1836, in __call__
    return self.wsgi_app(environ, start_response)
  File "C:\Users\mundia\OneDrive\101Python\popFlaskPaginate\popFlaskPaginate\venv\lib\site-packages\flask\app.py", line 1820, in wsgi_app
    response = self.make_response(self.handle_exception(e))
  File "C:\Users\mundia\OneDrive\101Python\popFlaskPaginate\popFlaskPaginate\venv\lib\site-packages\flask\app.py", line 1403, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Users\mundia\OneDrive\101Python\popFlaskPaginate\popFlaskPaginate\venv\lib\site-packages\flask\app.py", line 1817, in wsgi_app
    response = self.full_dispatch_request()
  File "C:\Users\mundia\OneDrive\101Python\popFlaskPaginate\popFlaskPaginate\venv\lib\site-packages\flask\app.py", line 1477, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "C:\Users\mundia\OneDrive\101Python\popFlaskPaginate\popFlaskPaginate\venv\lib\site-packages\flask\app.py", line 1381, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Users\mundia\OneDrive\101Python\popFlaskPaginate\popFlaskPaginate\venv\lib\site-packages\flask\app.py", line 1475, in full_dispatch_request
    rv = self.dispatch_request()
  File "C:\Users\mundia\OneDrive\101Python\popFlaskPaginate\popFlaskPaginate\venv\lib\site-packages\flask\app.py", line 1461, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "C:\Users\mundia\OneDrive\101Python\popFlaskPaginate\popFlaskPaginate\routes.py", line 263, in search_results
    pagination=pagination,
  File "C:\Users\mundia\OneDrive\101Python\popFlaskPaginate\popFlaskPaginate\venv\lib\site-packages\flask\templating.py", line 128, in render_template
    context, ctx.app)
  File "C:\Users\mundia\OneDrive\101Python\popFlaskPaginate\popFlaskPaginate\venv\lib\site-packages\flask\templating.py", line 110, in _render
    rv = template.render(context)
  File "C:\Users\mundia\OneDrive\101Python\popFlaskPaginate\popFlaskPaginate\venv\lib\site-packages\jinja2\environment.py", line 989, in render
    return self.environment.handle_exception(exc_info, True)
  File "C:\Users\mundia\OneDrive\101Python\popFlaskPaginate\popFlaskPaginate\venv\lib\site-packages\jinja2\environment.py", line 754, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Users\mundia\OneDrive\101Python\popFlaskPaginate\popFlaskPaginate\templates\searchResults.html", line 1, in top-level template code
    {% extends 'base.html' %}
  File "C:\Users\mundia\OneDrive\101Python\popFlaskPaginate\popFlaskPaginate\templates\base.html", line 51, in top-level template code
    {% block body %}{% endblock %}
  File "C:\Users\mundia\OneDrive\101Python\popFlaskPaginate\popFlaskPaginate\templates\searchResults.html", line 21, in block "body"
    {{ pagination.links }}
  File "C:\Users\mundia\OneDrive\101Python\popFlaskPaginate\popFlaskPaginate\venv\lib\site-packages\jinja2\environment.py", line 408, in getattr
    return getattr(obj, attribute)
  File "C:\Users\mundia\OneDrive\101Python\popFlaskPaginate\popFlaskPaginate\venv\lib\site-packages\flask_paginate\__init__.py", line 340, in links
    if self.total_pages <= 1:
  File "C:\Users\mundia\OneDrive\101Python\popFlaskPaginate\popFlaskPaginate\venv\lib\site-packages\flask_paginate\__init__.py", line 206, in total_pages
    pages = divmod(current_total, self.per_page)
TypeError: unsupported operand type(s) for divmod(): 'unicode' and 'int'

Please upload version 0.3.1 to PyPI.

Version 0.3.1 has a quoting fix I'm eager to start using (thank you very much for the fix!) but although PyPI has 0.3.1 as an allowed version:

https://pypi.python.org/pypi/Flask-paginate

...there's no downloads available for that version, which means it can't be automatically installed by tools like Pip.

Incorrect right-most window value on outer_window=0

I noticed a small bug when I was using this library. Here's the code I was using:

from flask import request

...

    def my_view():

    ...

    page_num = int(request.args.get('page', 1))
    per_page = int(request.args.get('per_page', 10))
    page = MySQLAlchemyModel.query.paginate(page=page_num, per_page=per_page)
    pagination = Pagination(page=page_num, per_page=per_page, search=True,
                            found=(per_page * page.pages), bs_version=3,
                            record_name='my_sqlalchemy_model', outer_window=0,
                            total=(per_page * page.pages))
    ...

Yeah, I'm approximating the found and total parameters there, but the result is that I get this on the page:

screen shot 2017-05-27 at 10 23 58

Ideally, only the last page (page 17) would show after the right ellipsis, not page 16 also.

typo documentation

i followed paging tutorial from http://pythonhosted.org/Flask-paginate, i got an error "count() takes exactly one argument (0 given)". i used python 2.7

documentation code:

pagination = Pagination(page=page, total=users.count(), search=search, record_name='users')

and problem solved after edit the Pagination total arg:

pagination = Pagination(page=page, total=len(galons), search=search, record_name='galon')

python3.6 support

please add support for python3.6, python3.4 is reaching the end-of-life in 2019

does this support mongodb

I'm using mongodb as my project's database, I just wonder does your plugin support mongodb or not? thank you!

why we need passing css_framework and alignment to Pagination function

i did set the variables css_framework and alignment in the config.py file

PER_PAGE = 10
CSS_FRAMEWORK = 'bootstrap4'
SHOW_SINGLE_PAGE = False
ALIGNMENT = 'center'
LINK_SIZE = 'sm'

and i check from app.config it did show the value for css_framework and alignment variables

<Config {'DEBUG': True, 'TESTING': False, 'PROPAGATE_EXCEPTIONS': None, 'PRESERVE_CONTEXT_ON_EXCEPTION': None, 'SECRET_KEY': 'À\x1fPr;%2HÍ1$/©Ë\nZ\x89\x8e^2Þ»üC', 'PERMANENT_SESSION_LIFETIME': datetime.timedelta(31), 'USE_X_SENDFILE': False, 'LOGGER_NAME': 'flask_app', 'LOGGER_HANDLER_POLICY': 'always', 'SERVER_NAME': None, 'APPLICATION_ROOT': None, 'SESSION_COOKIE_NAME': 'session', 'SESSION_COOKIE_DOMAIN': None, 'SESSION_COOKIE_PATH': None, 'SESSION_COOKIE_HTTPONLY': True, 'SESSION_COOKIE_SECURE': False, 'SESSION_REFRESH_EACH_REQUEST': True, 'MAX_CONTENT_LENGTH': None, 'SEND_FILE_MAX_AGE_DEFAULT': datetime.timedelta(0, 43200), 'TRAP_BAD_REQUEST_ERRORS': False, 'TRAP_HTTP_EXCEPTIONS': False, 'EXPLAIN_TEMPLATE_LOADING': False, 'PREFERRED_URL_SCHEME': 'http', 'JSON_AS_ASCII': True, 'JSON_SORT_KEYS': True, 'JSONIFY_PRETTYPRINT_REGULAR': True, 'JSONIFY_MIMETYPE': 'application/json', 'TEMPLATES_AUTO_RELOAD': None, 'ALIGNMENT': 'center', 'BASEDIR': '/mnt/website/WORKING/website_crawler/config', 'BCRYPT_LOG_ROUNDS': 10, 'CELERYD_LOG_FILE': '/mnt/website/WORKING/website_crawler/config/celery.log', 'CELERY_BROKER_URL': 'redis://localhost:6379/0', 'CELERY_RESULT_BACKEND': 'redis://localhost:6379/1', 'CSS_FRAMEWORK': 'bootstrap4', 'DEBUG_TB_INTERCEPT_REDIRECTS': False, 'LINK_SIZE': 'sm', 'PER_PAGE': 15, 'SHOW_SINGLE_PAGE': False, 'SQLALCHEMY_DATABASE_URI': 'sqlite:////mnt/website/WORKING/website_crawler/config/app.db', 'SQLALCHEMY_TRACK_MODIFICATIONS': False, 'TOP_LEVEL_DIR': '/mnt/website/WORKING/website_crawler', 'WTF_CSRF_ENABLED': True, 'SQLALCHEMY_BINDS': None, 'SQLALCHEMY_NATIVE_UNICODE': None, 'SQLALCHEMY_ECHO': False, 'SQLALCHEMY_RECORD_QUERIES': None, 'SQLALCHEMY_POOL_SIZE': None, 'SQLALCHEMY_POOL_TIMEOUT': None, 'SQLALCHEMY_POOL_RECYCLE': None, 'SQLALCHEMY_MAX_OVERFLOW': None, 'SQLALCHEMY_COMMIT_ON_TEARDOWN': False}>

pagination = Pagination(page=page,per_page=per_page, record_name='vtvs', total=total)

the function did not render the html properly
to make it works. i have to set

pagination = Pagination(css_framework='bootstrap4', page=page, alignment='center', per_page=per_page, record_name='vtvs', total=total)

Dosn't render links properly

view:

@blueprint.route('/', methods=['GET', 'POST'])
@login_required
@admin_required
def members():
    form = SearchMember(request.form, csrf_enabled=False)
    try:
        page = int(request.args.get('page', 1))
    except ValueError:
        page = 1

    search = False
    per_page = 15
    offset = (page - 1) * per_page

    if form.validate_on_submit():
        search = True
        q = form.search.data
        users = User.query.filter(or_(User.first_name.like(q),
                                      User.last_name.like(q),
                                      User.phone.like(q)))\
            .offset(offset)\
            .limit(per_page)
    else:
        users = User.query.offset(offset).limit(per_page)

    pagination = Pagination(page=page,
                            total=users.count(),
                            per_page=per_page,
                            search=search,
                            record_name='users',
                            css_framework='bootstrap3')

    return render_template("admin/members.html",
                           users=users,
                           page=page,
                           per_page=per_page,
                           pagination=pagination,
                           form=form)

Template:


{% extends "layout.html" %}

{% block content %}
<div class="body-content">
    <form id="searchForm" method="POST" action="" role="form">
    <div class="container">
        <div class="col-sm-6 col-sm-offset-3">
            <div id="imaginary_container">
                <div class="input-group stylish-input-group">
                    {{ form.hidden_tag() }}
                    {{ form.search(placeholder="Søk etter en bruker ved hjelp av før-/etternavn eller telefon nummer", class_="form-control") }}
                    <span class="input-group-addon">
                        <button type="submit">
                            <span class="glyphicon glyphicon-search"></span>
                        </button>
                    </span>
                </div>
            </div>
        </div>
    </div>
    </form>
    {{ pagination.links }}
    <table class="table table-condensed table-striped">
        <thead>
            <tr class="text-center">
                <td><b>Fornavn</b> <a href="?sort_on=first_name"><i class="fa fa-sort-asc"></i></a> <a href="?sort_on=first_name&reverse=1"><i class="fa fa-sort-desc"></i></a></td>
                <td><b>Etternavn</b> <a href="?sort_on=first_name"><i class="fa fa-sort-asc"></i></a> <a href="?sort_on=last_name&reverse=1"><i class="fa fa-sort-desc"></i></a></td>
                <td><b>E-mail</b> <a href="?sort_on=email"><i class="fa fa-sort-asc"></i></a> <a href="?sort_on=email&reverse=1"><i class="fa fa-sort-desc"></i></a></td>
                <td><b>Registrert</b> <a href="?sort_on=created_at"><i class="fa fa-sort-asc"></i></a> <a href="?sort_on=created_at&reverse=1"><i class="fa fa-sort-desc"></i></a></td>
                <td><b>Studierettning</b> <a href="?sort_on=study"><i class="fa fa-sort-asc"></i></a> <a href="?sort_on=study&reverse=1"><i class="fa fa-sort-desc"></i></a></td>
                <td><b>Telefon</b></td>
                <td><b>Aktiv</b></td>
                <td><b>Admin</b></td>
            </tr>
        </thead>
        <tbody>
            {% set sort_on = request.args.sort_on|default('id') %}
            {% set rev = request.args.get('reverse')|default(False)|int %}
            {% for user in users|sort(attribute=sort_on, reverse=rev) %}
            <tr class="text-center">
                <td>{{ user.first_name }}</td>
                <td>{{ user.last_name }}</td>
                <td>
                    <a href="mailto:{{ user.email }}">{{ user.email }}</a>
                </td>
                <td>{{ user.created_at }}</td>
                <td>{{ user.study }}</td>
                <td>{{ user.phone }}</td>
                <td>
                    <a href="{{ url_for('admin.user', type='state', uid=user.id) }}">
                        <i>
                            <span class="glyphicon glyphicon-{% if user.active %}ok{% else %}remove{% endif %}"></span>
                        </i>
                    </a>
                </td>
                <td>
                    <a href="{{ url_for('admin.user', type='admin', uid=user.id) }}">
                        <i>
                            <span class="glyphicon glyphicon-{% if user.is_admin %}ok{% else %}remove{% endif %}"></span>
                        </i>
                    </a>
                </td>
            </tr>
            {% endfor %}
        </tbody>
    </table>
    {{ pagination.links }}
    {{ pagination.info }}
</div>
{% endblock %}

Result:
image

What am I doing wrong? I followed the example code.

There are 23 users in the database

Flask Pagination not working for Page Number 1

Pagination working properly when we moving from page n to page 1.
For Ex:
Case 1. If We move from page 1 to 2 filters are kept as it is and works properly.
Formed Url: http://localhost:5000/stats/trafficlog?page=2
Case 2. If We move from page 2 to others(except 1) filters are kept as it is.
Formed URL is: http://localhost:5000/stats/trafficlog?page=50497
But not working for
For Ex:
Case 1: If we from Other pages to page 1, it resets all filters.
Formed URL http://localhost:5000/stats/trafficlog

But for proper pagination it should be http://localhost:5000/stats/trafficlog?page=1

Am i missing something
Please correct me

If we change the code as following working properly

image

Generating wrong url with parameter(s)

I come into a problem that the page links are generated incorrectly when the paginated view has parameter(s). For example, my view has following definition:

@route('/something/<param>')
def something(param):
...

and the generated url links are like this:
http://xxxxxx/something/[u'param']?page=2

This seems to be an issue of the args property, as it passes a MultiDict to url_for as kwargs which wrongly parses the param string into a list.
I solved this by changing

if PY2:
    args_items = request.args.iteritems(multi=True)
else:
    args_items = request.args.items(multi=True)
args = MultiDict(list(args_items) + list(request.view_args.items()))

into

args_items = request.args.items()
args = dict(args_items + request.view_args.items())

And everything works fine.

Hope to solve this issue in new release.

Include test script to pypi release

Please include tests scripts on the next pypi release, it will make it easier for maintainers. Also I think it can be useful to also create github tags for the releases¿?

Thank you.

UndefinedError: 'flask_paginate.Pagination object' has no attribute 'skip'

网页加上这句话会报错

{{ loop.index + paginate.skip }} 后台代码如下

def index():
search = False
q = request.args.get('q')
if q:
search = True

page = request.args.get(get_page_parameter(), type=int, default=1)
per_page = int(request.args.get('per_page', 2))

print(page,per_page)
selectdata = User.query.filter_by(password='123456').all()



paginate = Pagination(page=1, total=len(selectdata), search=search, record_name='users',per_page= per_page,per_page_parameter = 'per_page')
#paginate = selectdata.paginate(page, per_page, error_out=False)
#stus = paginate.items

return render_template('index.html',
                       stus=selectdata,
                       paginate=paginate,
                       )

Doesn't work for Bootstrap3

In Bootstrap3 they left "pagination" class unchanged, but moved it from "div" to inner "ul" element. So, styling doesn't work.

pagination links are not showing

I have installed flask-paginate using $ pip install flask-paginate for my flask application
and i have added css, html code as mentioned in this page

am able to render the objects and and paginate.info but the links are not showing like bellow image

paginate-links

and my view is

@app.route('/')
def index():
search = False
q = request.args.get('q')
if q:
    search = True

users = Onboard.query.all()
pagination = Pagination(users.count, search=search,total = 2, per_page=2, inner_window=2, outer_window=2, record_name='users')
return render_template('index.html',
                       users=users,
                       pagination=pagination,
                       )

<table><tr><td></td></tr></table>```

can you please help to show the page links and if i click on that page i need to get respective objects
how can i achieve this functionality
I apologize for my bad English
Thanks in advance

Python 3.4 support

I use python 3.4 and Flask 0.10.1
Pagination.links gets an exeption AttributeError: 'ImmutableMultiDict' object has no attribute 'iteritems'
on this line:
https://github.com/lixxu/flask-paginate/blob/master/flask_paginate/__init__.py#L207

python
args = MultiDict(list(request.args.iteritems(multi=True)) + request.view_args.items())


This fork works well: https://github.com/nesforge/flask-paginate
Patch: https://github.com/nesforge/flask-paginate/commit/6ea9b821e14e1a92884bf2ebd152cf400caa42e9

HTML Escaping of Links

In my view template, I render links like this:

{{ pagination.links|safe }}

However, this is how they appear:

<a href="/blog%3Fpage%3D2">2</a>

It appears the |safe filter isn't working, since the URL should be like this:

<a href="/blog?page=2">2</a>

Does anyone else have this issue? Python 3.4

about search

i have a problem about search,firstly, about how to configure,i see few aspect about search on the docs and i see the souce code there are two parameters(search and found),so i want to know how configure search.secondly,it's about the search result. is there only one display result that is on the docs that found <b>{found}</b> {record_name}, displaying <b>{start} - {end}</b> ?can it show results in the table after searching?

How to process forms

So if I have a form that as 50 entries but each page has ten entries so in total 5 pages, but each entry has a radio button, if I select a radio button on page 1 and page 5, will the data get posted through? As I am using the sql-alchemey on and it is not working

Won't play nice with URLs containing double quotes

Pagination will break if the URL contain double quotes (ie. hrefs containing JSON strings).

You should be fine using the url_for directly instead of unquotting it later with urllib in get_link.

Replacing:

return self.get_link(url_for(self.endpoint, page=page, **self.args))

With:

return url_for(self.endpoint, page=page, **self.args)

Did the trick for me and should not affect other cases/scenarios.

add Python 3 trove classifiers

it looks like this project supports Python 3 just fine, would you mind adding Py3 trove classifiers?

e.g.

Programming Language :: Python :: 3.3
Programming Language :: Python :: 3.4

update to bootstrap 3 or 4

Bootstrap 2 is quite old and is not supported officially. Do you guys have a plan of upgrade flask-paginate to bootstrap 3 or bootstrap 4?

Disabled links redirects to #

When you click on a disabled link it takes you to the top of the page, because href is set to #.
It can get annoying and hurt OCD if content per page is more than 10 or 20.

A fix would be to remove the href attribute from disabled links.

pagintation.links() does not work

I'm having a problem with pagination.links, which is not outputting any links.

I've added pagination.links() to my view to see what the output was, but that raised an error:

Traceback (most recent call last):
  File "/Users/Nicolas/myproject/flask/lib/python3.3/site-packages/flask/app.py", line 1836, in __call__
    return self.wsgi_app(environ, start_response)
  File "/Users/Nicolas/myproject/flask/lib/python3.3/site-packages/flask/app.py", line 1820, in wsgi_app
    response = self.make_response(self.handle_exception(e))
  File "/Users/Nicolas/myproject/flask/lib/python3.3/site-packages/flask/app.py", line 1403, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/Users/Nicolas/myproject/flask/lib/python3.3/site-packages/flask/_compat.py", line 33, in reraise
    raise value
  File "/Users/Nicolas/myproject/flask/lib/python3.3/site-packages/flask/app.py", line 1817, in wsgi_app
    response = self.full_dispatch_request()
  File "/Users/Nicolas/myproject/flask/lib/python3.3/site-packages/flask/app.py", line 1477, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/Users/Nicolas/myproject/flask/lib/python3.3/site-packages/flask/app.py", line 1381, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/Users/Nicolas/myproject/flask/lib/python3.3/site-packages/flask/_compat.py", line 33, in reraise
    raise value
  File "/Users/Nicolas/myproject/flask/lib/python3.3/site-packages/flask/app.py", line 1475, in full_dispatch_request
    rv = self.dispatch_request()
  File "/Users/Nicolas/myproject/flask/lib/python3.3/site-packages/flask/app.py", line 1461, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/Users/Nicolas/myproject/flask/lib/python3.3/site-packages/flask_login.py", line 758, in decorated_view
    return func(*args, **kwargs)
  File "/Users/Nicolas/myproject/app/util/__init__.py", line 22, in decorated_function
    return func(*args, **kwargs)
  File "/Users/Nicolas/myproject/app/lab/views.py", line 206, in inventory
    pagination.links()
  File "/Users/Nicolas/myproject/flask/lib/python3.3/site-packages/flask_paginate/__init__.py", line 356, in links
    s.append(self.single_page(page) if page else self.gap_marker_fmt)
  File "/Users/Nicolas/myproject/flask/lib/python3.3/site-packages/flask_paginate/__init__.py", line 330, in single_page
    return LINK.format(self.page_href(page), page)
  File "/Users/Nicolas/myproject/flask/lib/python3.3/site-packages/flask_paginate/__init__.py", line 202, in page_href
    return url.decode('utf8')
AttributeError: 'str' object has no attribute 'decode'

Changing return url.decode('utf8') to return url
fixes the problem.

I'm working with Python 3.3, flask-paginate 0.3.0.

A single page returns no links.

If a single page is returned, flask-paginate assumes that we don't want any pagination links:

@property
def links(self):
    '''get all the pagination links'''
    if self.total_pages <= 1:
        return ''
    ...

This isn't a totally unreasonable assumption. However it breaks the layout of pages which always expect some pagination element, even if it only represents a single page.

An option like show_single_page should be provided, (with a default value of False to preserve the existing behaviour). This would allow the user to decide whether or not a single page returns pagination.

Not an Issue: not finding a way to pass query params to flask using flask paginate.

My code -
pagination = Pagination(page=int(pageno), per_page=10, found = json_response['count'], total=json_response['count'], total_pages=json_response['pages'], search=True, record_name='requests', css_framework='bootstrap4', **{"name":request_name})

However, I am not getting the name anywhere in the pagination object created above even after passing that as **kwargs. I want name attribute as part of query param in a flask or at least a way to get it when I do request.args.get('name') whenever I click on the link created from {{ pagination.links }} eg -

@app.route("/search", methods=['GET', 'POST'])
def search():
if form.validate_on_submit():
request_name = request.args.get('name', form.requestname.data)
pageno = request.args.get('page', 1)

search.html
{{ pagination.info }}
{{ pagination.links }}

Sample links creatd as part of above code -
http://127.0.0.1:5000/search?page=1
http://127.0.0.1:5000/search?page=2
etc.

0

Adding Additional querystring parameters

Is it possible to add additional querystring parameters to the links generated by the plugin. I have some filtering parameters on the page that I'd like to send while loading the second page

pagination.links的样式不对.

你好,不知道是不是因为bootstrap的版本原因,需要这样写才能够正确的显示,

    可是默认的市
    .
    请问这个问题应该如何解决呢?谢谢你呢

Pagination links not parsing variables correctly

Hi,

For a URL like this:
/location/america
@application.route("/location/string:name")

The pagination.links are showing as:
/location/[u'america']?page=x

From pythonhosted website:
Latest version: 0.2.4

Installed today.

If you need anymore information just shout.
Thanks.

TypeError: url_for() got multiple values for keyword argument 'page'

File "/opt/python-2.7.10/lib/python2.7/site-packages/flask_paginate/__init__.py", line 349, in links s.append(self.single_page(page) if page else self.gap_marker_fmt) File "/opt/python-2.7.10/lib/python2.7/site-packages/flask_paginate/__init__.py", line 323, in single_page return self.link.format(self.page_href(page), page) File "/opt/python-2.7.10/lib/python2.7/site-packages/flask_paginate/__init__.py", line 220, in page_href url = url_for(self.endpoint, page=page, **self.args) TypeError: url_for() got multiple values for keyword argument 'page'

page is already in **self.args

Paginate shows up all results on same page

I am using Flask-paginate for pagination in my app. The results are fetched from database. The problem is that all results show up on 1st page and when I click on the next page number again all results are displayed on that page. The page number in url changes to 2/3/4 etc. I this as reference. Here is my code snippet

from flask.ext.paginate import Pagination
    @app.route('/users')
    def users_page():

        page_size = 25
        limit = 100

        search = False
        q = request.args.get('q')
        if q:
            search = True
        try:
            page = int(request.args.get('page', 1))
        except ValueError:
            page = 1
        with session_scope() as session:
            users = users_dao.get_users(session, limit=limit)
            pagination = Pagination(page=page, total=len(users), per_page=page_size, search=search, record_name='users')
            return render_template("users.html", users=users, pagination=pagination)

The pagination info on html page says displaying 1-25 results of 100. When clicked on page 2, it says displaying 25-50 results of 100. So somehow the pagination has figured out on the basis of total and per_page how many results should be displayed but somewhere it fails to force that on number of rows to show.

The template looks like

{{ pagination.info }}
    <table class="table">
        <thead>
            <tr>
                <th>#</th>
                <th>User Name</th>
                <th>Phone</th>
                <th>City</th>
                <th>Country</th>
            </tr>
        </thead>
        <tbody>
            {% for user in users %}
            <tr>
                <td>{{loop.index + users.skip}}</td>
                <td>{{ user.user_name }}</td>
                <td>{{ user.phone_number }}</td>
                <td>{{user.city}}</td>
                <td>{{user.country}}</td>
            </tr>
            {% endfor %}
        </tbody>
    </table>
    {{ pagination.links }}

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.