Ash Mohatt
Ash Mohatt

Reputation: 23

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?

Upvotes: 1

Views: 1220

Answers (2)

pjcunningham
pjcunningham

Reputation: 8046

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

Upvotes: 4

Filipe Amaral
Filipe Amaral

Reputation: 1723

If you are asking how protect this link it you depends on how you are handle user accounts. I usually do it with Flask-Login and a method on User Model that returns True if user is an admin, see this snippet:

{% if current_user.is_admin() %}
 <a href="/admin" style="color:red">Admin</a>
{% endif %}

the current_user passed by Flask-Login to the template.

Upvotes: 0

Related Questions