Remember pagination form data

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) # My template contains this form and a regular HTML table <form action="{{ url_for('browse') }}" method="POST"> {{ form.hidden_tag() }} {{ form.sort.label }} {{ form.sort() }} {{ form.filter.label }} {{ form.filter() }} <button type="submit" class="btn">Submit</button> </form> 
+6
source share
2 answers

You can use URL parameters to pass sorting information. Say the user selects a sort by name. Then add this to the end of the url

  your_url?sort=name 

Then you can access it as

  value = request.args.get('name','') 

Just pass the value of the sort variable to the template, where you add the sort value to the following URL.

Edit:

To create such a URL in Flask, do the following:

  url_for('url_view_name', sort='name') 

This will return the URL with the sort added as an argument to the request. Check the flask documentation here to learn more about building URLs.

+7
source

You can do this with Javascript. Since the page number is part of your URL, you can change the javascript action form, which changes the page to send the URL with the desired page number instead of the current page.

To clarify when the user clicks the "next" button / button or page number, use Javascript to change the action of the html form so that it sends the form to the desired page instead of the current page.

0
source

Source: https://habr.com/ru/post/924195/


All Articles