I’m developing a Flask web application that allows users to search for books and view their details. However, I’m facing an issue where the form isn’t sent to the URL.
Here’s a simplified version of my code:
python
Copy code
bookshelf = utils.bookshelf
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
tgt = request.form.get("bookname")
return render_template('found.html', bookname=tgt)
return render_template('index.html', books=bookshelf)
@app.route('/found/<string:bookname>', methods=['GET', 'POST'])
def found(bookname):
located = True
book = None
if request.method == 'POST':
if bookname:
for book in bookshelf:
if bookname.lower() == book['title'].lower():
return render_template('found.html', book=book)
located = False
return render_template('found.html', error="Book not found")
else:
for book in bookshelf:
if bookname.lower() == book['title'].lower():
return render_template('found.html', book=book)
return render_template('found.html', book=book, error="Book not found")
And here’s the html template:
html
Copy code
{% extends "layout.html" %}
{% block title %}
Homepage
{% endblock %}
{% block main %}
<h1 class="name-port">Welcome to Sorted Tales</h1>
<h1>
<form action="{{ url_for('found', bookname=bookname) }}" method="post">
<div>
<input type="text" name="bookname" placeholder="Type the name of a book"/>
</div>
<div>
<button style="background-color: #009879;" type="submit">Search</button>
</div>
</form>
<table class="content-table">
<thead>
<tr class="heading">
<th>Book Name</th>
<th>Author</th>
</tr>
</thead>
<tbody>
{% for book in books %}
<tr>
<td><a style = "color:#000000;"href="/found/{{ book.title }}">{{ book.title }}</a></td>
<td>{{book.author_information[0]["name"]}}</td>
</tr>
{% endfor %}
</tbody>
</table>
</h1>
{% endblock %}
However, regardless of the input, the application always displays the 404 error and the bookname isn’t added to the URL
What could be causing this issue? Any help would be greatly appreciated. Thank you!
I have verified that the bookshelf data contains the correct book information, and I’m using a case-insensitive comparison for the search.
2
Answers
Instead of making the post route dynamic, try changing the route to just ‘/found’, without taking bookname as a parameter.
request.form will already contain all the values that you have named inputs for in the HTML form.
I think it does not work because in render_template method, you pass the variable book, but in the template you use the variable bookname. I think it should be
"{{ url_for('found', bookname=book) }}"