In my Flask application, I have a view that displays a table of elements using the Flask-SQLAlchemy pagination method. Still. But I want to add sorting and filtering, so I created a form with selectboxes where the user can select the sorting and filtering options.
When sending a sort / filter on a page, the view works fine: the first page is sorted. But by selecting another page on the page, pagination returns to the original request. What to do to save sorting / filtering options while loading a new page? Using flask.g came up to me, but is this true?
class ItemTableForm(Form): sort_choices = [('id', 'ID'), ('name', 'Name'), ('status', 'Status')] filter_choices = [('all', 'All'), ('instock', 'In stock'), ('sold', 'Sold')] sort = SelectField(u'Sort by', choices=sort_choices) filter = SelectField(u'Filter by', choices=filter_choices) @app.route('/browse/<int:page>', methods=("GET", "POST")) def browse(page): form = ItemTableForm() if form.validate_on_submit(): query = Item.query.order_by(getattr(Item, form.sort.data)) else: query = Item.query pagination = paginate(query, page) return render_template('browse.html', pagination=pagination, form=form)
source share