-1

I am trying to implement a basic search bar functionality to my site.

I will process the actual search on my database later but at the moment I am trying to just send the request, which will simply be a string from my search bar to my search route.

I have my search bar form:

<form class="form-inline" action="{{ url_for('search') }}">
  <input class="form-control" type="search" placeholder="Search">
  <button class="btn btn-primary" type="submit">Search!</button>
</form>

and my route

@app.route('/search', methods=['GET', 'POST'])
def search():
    user_search = request.args['search']
    return render_template('results.html', search=user_search)

When I use my search bar I get the following error:

werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand.
KeyError: 'search'

I do not understand where I am going wrong.

davidism
  • 121,510
  • 29
  • 395
  • 339
jirzivuf
  • 29
  • 4

2 Answers2

0

Add the name attribute on the field to be able to access it as request.args['search'].

<input class="form-control" type="search" placeholder="Search" name="search">
AKX
  • 152,115
  • 15
  • 115
  • 172
  • OP will still get `KeyError` when they try to use `GET` no? maybe `request.args.get('search')` will be better – DeepSpace Apr 17 '20 at 18:23
0

That's because the request does not have "search" args. This can fix your problem:

<form class="form-inline" action="{{ url_for('search') }}">
  <input class="form-control" name="search" type="search" placeholder="Search">
  <button class="btn btn-primary" type="submit">Search!</button>
</form>

I added name "search" in the input.

clemsciences
  • 121
  • 9