I have a form in my template that when submitted, provides search filters for my database query. The query otherwise returns all documents. I am using flask-paginate to navigate the results.
My bug is, if the user is on page 2 when they submit the form, the page reloads page 2 with the results of the new query, even if the number of documents returned does not equate to more than 1 page. In this case, the page that loads is just blank and there are no pagination links to navigate back to page 1. So far, I have semi solved this by changing the value of flask-paginate's 'page' variable to equal 1 when the form is submitted. It now seems to load the results from page 1, when I print(page) it correctly prints '1'. However, the query string in the url still says ?page=2. I am therefore looking for a cleaner solution? or a way to clear the query string?
@app.route("/thingstodo/<city>", methods=["GET", "POST"])
def suggestion_list(city):
form = FilterResultsForm()
cities = mongo.db.cities
page, per_page, offset = get_page_args(
page_parameter="page", per_page_parameter="per_page"
)
print(page)
if form.validate_on_submit():
page = 1
per_page = 3
offset = (page - 1) * per_page
query = ""
if form.validate_on_submit() or "filters" in session:
filters = (
form.category.data if form.category.data else session["filters"]
)
session["filters"] = filters
array = []
for filter in filters:
newdict = {}
newdict["thingsToDo.category"] = filter
array.append(newdict)
query = cities.aggregate(
[
{"$unwind": "$thingsToDo"},
{"$match": {"location": city, "$or": array}},
{
"$lookup": {
"from": "users",
"localField": "thingsToDo.author",
"foreignField": "username",
"as": "user_profile",
}
},
{"$unwind": "$user_profile"},
{
"$project": {
"suggestion": "$thingsToDo.suggestion",
"cost": "$thingsToDo.cost",
"category": "$thingsToDo.category",
"url": "$thingsToDo.url",
"comment": "$thingsToDo.comment",
"author": "$user_profile.username",
"profile": "$user_profile.picture",
}
},
]
)
else:
query = cities.aggregate(
[
{"$match": {"location": city}},
{"$unwind": "$thingsToDo"},
{
"$lookup": {
"from": "users",
"localField": "thingsToDo.author",
"foreignField": "username",
"as": "user_profile",
}
},
{"$unwind": "$user_profile"},
{
"$project": {
"suggestion": "$thingsToDo.suggestion",
"cost": "$thingsToDo.cost",
"category": "$thingsToDo.category",
"url": "$thingsToDo.url",
"comment": "$thingsToDo.comment",
"author": "$user_profile.username",
"profile": "$user_profile.picture",
}
},
]
)
results = list(query)
total = len(results)
suggestions = results[offset: offset + per_page]
pagination = Pagination(
page=page, per_page=per_page, total=total, css_framework="bootstrap4"
)
return render_template(
"thingstodo.html",
city=city,
things=suggestions,
page=page,
per_page=per_page,
pagination=pagination,
form=form,
title="Things to do",
)