Reputation: 9814
Is there any way to modify the home button url link on the flask-admin admin top panel so that I redirect back to a main site?
I can add a link in a custom.html page eg:
{% extends 'admin/master.html' %}
{% block body %}
<a href="{{ url_for('main.home') }}">Home</a>
{% endblock %}
But this is hidden away inside the custom page. I'd prefer a top-bar link out of admin.
Upvotes: 3
Views: 6274
Reputation: 31
As you can see from a MenuLink initialization
If you need a url_for method for your MenuLink you should just set endpoint for your MenuLink instance instead of url, like:
admin.add_link(MenuLink(name='Home', endpoint='main.home'))
Upvotes: 0
Reputation: 109
If you are having issues with app context error when using app.app_context():
RuntimeError: Unable to build URLs outside an active request without 'SERVER_NAME' configured. Also configure 'APPLICATION_ROOT' and 'PREFERRED_URL_SCHEME' as needed.
You can simply 'test_request_context()' method.
with app.test_request_context():
admin.add_link(MenuLink(name='Name', category='', url=url_for('home.home_route')))
This is documented here
Upvotes: 1
Reputation: 360
You can override get_url
method of MenuLink
. That way you get around application context problem.
from flask import url_for
from flask_admin import Admin
from flask_admin.menu import MenuLink
class MainIndexLink(MenuLink):
def get_url(self):
return url_for("main.index")
admin = Admin(name="Admin")
admin.add_link(MainIndexLink(name="Main Page"))
def create_app():
app = Flask(__name__)
from app.admin import admin
admin.init_app(app)
return app
Upvotes: 3
Reputation: 8046
Easiest way is to add a menu link and leave the admin home page alone (you might want to add a dashboard or suchlike in the future):
from flask_admin.menu import MenuLink
# Create admin
admin = Admin(app, name='Admin', url='/')
admin.add_view(ImageView(model=Image, session=db.session, category='Database', name='Images'))
# Add custom link to public website home page
admin.add_link(MenuLink(name='Public Website', category='', url=url_for('main.home')))
Note, url_for
needs to be called within a Flask application context. For example, if using the Flask application factory pattern, this would look something like the following:
def create_app(config):
app = App('app')
# setup config
# setup blueprints
# setup Flask-Admin
from app.admin import create_admin
from app.admin.configure import configure_admin
with app.app_context():
admin = create_admin(app=app)
configure_admin(app, admin)
# more stuff
return app
__init__.py
in app.admin module
def create_admin(app=None):
return Admin(app, template_mode='bootstrap3')
configure.py
in app.admin module
def configure_admin(app, admin):
# setup views
# add link to home page
admin.add_link(MenuLink(name='Public Website', category='', url=url_for('home.HomeView:index')))
Upvotes: 9