Does url_for
work across blueprints?
/flaskapp
/runserver.py (from server import app; app.run(debug=True))
/server
/__init__.py (app = Flask(__name__))
/pages
/__init__.py ('pages' blueprint)
/users
/__init__.py ('users' blueprint)
in server/__init__.py
:
from server.pages import pages
from server.users import users
app = Flask(__name__)
app.register_blueprint(pages)
app.register_blueprint(users)
in server/pages/__init__.py
:
pages = Blueprint('pages', __name__)
@pages.route('/')
def index(): return '<h1>Index</h1>'
in server/users/__init__.py
:
users = Blueprint('users', __name__)
@users.route('/login')
def login():
...
return redirect(url_for('pages.index'))
^^^^^^^^^^^^^^^^^^^^^^
The url_for
call raises BuildError: ('pages.index', {}, None)
What would be a way to get to 'pages.index'
?
(I tried importing the module, but that didn't work)
As best I can tell, you're organizing your app the way you should.
I've recreated your setup (albeit in a single file), which you can checkout here. This code runs on my machine.
https://gist.github.com/enlore/80bf02346d6cabcba5b1
In flask, you can access a given view function with a relative endpoint (.login
) from within the owning blueprint, or an via an absolute one (user.login
) anywhere.
My money is on you having a typo in a view function name.
Like Mark Hildreth said in the comments, a great way to debug your problem would be to take a look at your url map.
>>> from app import app
>>> app.url_map
Map([<Rule '/login' (HEAD, OPTIONS, GET) -> user.login>,
<Rule '/' (HEAD, OPTIONS, GET) -> pages.index>,
<Rule '/static/<filename>' (HEAD, OPTIONS, GET) -> static>])
>>>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With