python flask url_for is throwing constant werkzeug build errors

Question:

I am having a flask url_for(”) error in a very simple application.

from flask import Blueprint, render_template, abort
from jinja2 import TemplateNotFound

base = Blueprint('main', __name__)

@base.route('/', defaults={'page':'home'})
@base.route('/<page>')
def show(page):
    try:
        return render_template('%s.html'%page, name='my name is')
    except TemplateNotFound:
        abort(404)

the above is my blueprints file, those routes work fine but if I try to do

with flask.test_request_context():
    print url_for('home') #home.html or any other forms

I just get this error:

raise BuildError(endpoint, values, method)
werkzeug.routing.BuildError: ('home', {}, None)

can anyone help me figure out what’s going on here?
in my html page I can print out the location of static files with:

{{ url_for('static', filename='style.css') }}

but if i try to do:

{{ url_for('home') }}

Again I get the same error. Anyone have some advise as how to proceed?

Asked By: steffan

||

Answers:

You’re trying to use url_for the wrong way round, I think.
url_for in general maps an endpoint, i.e. a python function/method, to an url. In your case home is the value of a parameter, not an endpoint.

So, instead, use the name of the python function you want the url for:

url_for('show', page='home')

Should be what you’re looking for.

Answered By: sebastian

When you do {{ url_for('home') }} it doesn’t return route of home.html instead it returns the route of a function home, which by the way doesn’t exist.

So to fix your problem,
The proper way of using url_for is :

{{ url_for('show') }}
Answered By: Alfie
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.