Question

Searched around/tinkered to no avail.

I am using flask, mongoengine, mongodb version 2.4.

I am trying to query my one of my collections (posts and specifically via tags).

These are my routes:

@notes_app.route('/search', methods= ["post"])
@login_required
def search():
    query = request.form.get('query')
    return redirect(url_for('search_results', query=query)

@notes_app.route('/search_results/<query>', methods=["post"])
@login_required
def search_results(query):
    posts = models.Post.objects(tag=query)
    return render_template('search_results.html', posts=posts)

This my search box in index.html

<form action='/search' method="post">
        <p><input type="text" name="query" value="test"></p>
        <p><input type="submit" value="Search"></p>
        <br />
      </form>

My traceback:

File "notes.py", line 75, in search
   return redirect(url_for('search_results', query=query))
File "python2.7/site-packages/flask/helpers.py", line 312, in url_for
   return appctx.app.handle_url_build_error(error, endpoint, values)
File "python2.7/site-packages/werkzeug/routing.py", line 1620, in build
   raise BuildError(endpoint, values, method)
   BuildError: ('search_results', {'query': u'coding'}, None)

Any advice is greatly appreciated, thanks!

Was it helpful?

Solution

When redirecting within a blueprint, you need to include the blueprint's name in the call to url_for.

If working with a blueprint defined like

notes_app = Blueprint('notes_app', __name__, template_folder='templates')

you would need to use

@notes_app.route('/search', methods=['POST'])
@login_required
def search():
    query = request.form.get('query')
    return redirect(url_for('notes_app.search_results', query=query)

OTHER TIPS

I am fairly certain the 'methods' argument is case-sensitive. I have a similar app and my code has all-caps methods=['GET', 'POST'], as do the flask docs. That may explain why your traceback is showing 'None' in the BuildError.

Also, your query variable looks like it's showing the entire key-value pair; if that's part of your application logic, that's fine, but mine is as follows:

query = request.args.get('query')

So, in my case, the query variable is just the string value, not the entire key-value pair. (Again though, your application logic may be set up differently.) Also, if you want to use 'request', you'll need to import it from flask.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top