Bryar
Bryar

Reputation: 131

Flash message not showing because of conditon

In flask, im trying to flash a message when there are no results from the user's search. Problem is, the flash is not doing its job. I believe its because of the if condition but im not sure why.

If i make this the condition: if counter == 0: then flash , it works. But even when the user is just reloading the search page, the message gets flashed so its not desirable. That why im trying to create the condition based on book.query & this is where im stuck.

@app.route("/search", methods=['GET', 'POST'])
def search():
    keyword = escape(request.form.get("keyword"))
    books = Book.query.filter(or_(Book.isbn.like(f'%{keyword}%'), Book.title.like(
        f'%{keyword}%'), Book.author.like(f'%{keyword}%'))).all()
    counter = Book.query.filter(or_(Book.isbn.like(f'%{keyword}%'), Book.title.like(
        f'%{keyword}%'), Book.author.like(f'%{keyword}%'))).count()

    if books is None:
        flash('No matches found!', 'info')

    return render_template('search.html', title='Search', books=books)

Upvotes: 0

Views: 36

Answers (1)

Jürgen Gmach
Jürgen Gmach

Reputation: 6141

In your query for books you use .all() at the end.

.all() returns a list - in case of no result, this will be an empty list, but you compare the result to None.

While both None and [] are falsy values, they are not identical.

But you explicitly compare object identity with the is keyword.

So you could change your if guard to

if not books:

or

if len(books) == 0:

Make sure to tell us how it worked out!

Upvotes: 1

Related Questions