Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remember form data for pagination

In my Flask application, I have a view which renders a table of items by using the Flask-SQLAlchemy pagination method. Great stuff so far. But I want to add sorting and filtering, so I created a form with selectboxes where the user can choose the sort and filter options.

When submitting the sort/filter on the page, the view works fine: the first page is sorted. But selecting another page on the page, the pagination is falling back to the original query. What should I do to save my sort/filter options during new page loads? Using flask.g has come up to me, but is it the correct way?

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>
like image 754
Timo Avatar asked Aug 30 '12 18:08

Timo


1 Answers

You can use url parameters to pass the info about sorting. Say user selects sorting by name. Then add this at the end of url

    your_url?sort=name

Then you can access it as

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

Simply pass sorting variable value to the template where you append sort value to the next url.

Edit:

To create such url in Flask, do this:

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

This will return the url with sort appended as query argument. Check out the flask documentation here to know more about url building

like image 72
codecool Avatar answered Sep 21 '22 12:09

codecool