Search code examples
htmlflask

Flask-Admin link back to main site


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.


Solution

  • 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')))