Search code examples
flaskflask-admin

How do you link from a main page (index.html) in python Flask to the admin section which is using Flask-admin?


I'm using flask in a first project. What method do I need to add a link to the admin section from a main page in the site?


Solution

  • The default URL route is /admin. You can get also get the default route using url_for('admin.index').

    Note that it's possible to have more that one flask-admin instance per Flask application. See self-contained snippet below that illustrates this.

    from flask import Flask, url_for, render_template_string
    from flask_admin import Admin
    
    app = Flask(__name__)
    
    default_admin = Admin()
    default_admin.init_app(app)
    
    admin_1 = Admin(endpoint="another", url="/another")
    admin_1.init_app(app)
    
    admin_2 = Admin(endpoint="this_is_a_long_endpoint", url="/this_is_a_long_url")
    admin_2.init_app(app)
    
    admin_3 = Admin(endpoint="test", url="/test/test")
    admin_3.init_app(app)
    
    # admin_exception_1 = Admin()
    # admin_exception_1.init_app(app)
    # This has the same endpoint as default_admin - not allowed
    # Cannot have two Admin() instances with same endpoint name.
    
    # admin_exception_2 = Admin(endpoint="admin1", url="/admin")
    # admin_exception_2.init_app(app)
    # This has the same url as default_admin - not allowed
    # Cannot assign two Admin() instances with same URL and subdomain to the same application.
    
    index_template = """
        <table>
            <thead>
                <tr>
                    <th>URL</th>
                    <th>Endpoint</th>
                </tr>
            </thead>
        <tbody>
            {% for link in links %}
                <tr>
                  <td>{{ link.url }}</td>
                  <td>{{ link.endpoint }}</td>
                </tr>
            {% endfor %}
        </tbody>
        </table>
    """
    
    
    @app.route('/')
    def index():
        _links = []
        _endpoints = ['admin.index', 'another.index', 'this_is_a_long_endpoint.index', 'test.index']
        for _endpoint in _endpoints:
            _links.append(
                {
                    'url': url_for(_endpoint),
                    'endpoint': _endpoint
                }
            )
        return render_template_string(index_template, links=_links)
    
    
    if __name__ == '__main__':
        app.run(port=7000, debug=True)
    

    Sample Output

    Flask-Admin urls and endpoints