Flask-Admin Documentation

repository·master·Indexed 26 days ago

https://github.com/pallets-eco/flask-admin

A flexible, batteries-included admin interface framework for Flask (version 2.2.0). It provides extensible CRUD views and supports multiple ORMs including SQLAlchemy, MongoDB, and Peewee. Key features include file management for local, S3, and Azure storage, a Redis client console, GeoAlchemy GIS support, and deep customization options for forms, views, and localization via Flask-Babel.

Tokens
14.1K
Snippets
39
Records
95
Agent score
91%

What's inside Flask-Admin

  1. Overview of Flask-Admin features

    master

    Flask-Admin is a batteries-included extension for Flask that provides admin interfaces. It is designed to be highly flexible, allowing developers to customize look, feel, and functionality.

    Key features include:

    • ORM Support: Works out-of-the-box with SQLAlchemy (via Flask-SQLAlchemy or Flask-SQLAlchemy-Lite), pymongo, MongoEngine, and Peewee.
    • File Management: Includes a simple interface for managing files.
    • Redis Support: Provides a Redis client console.
    • Customization: Supports auto-generated CRUD views that can be further customized via views and forms.
  2. Extend built-in Flask-Admin templates

    master

    Instead of replacing templates, extend them to ensure compatibility with future updates. The most common templates to extend are:

    • admin/model/list.html
    • admin/model/create.html
    • admin/model/edit.html

    To use a custom template for a specific view, set the corresponding class property (e.g., edit_template, list_template, create_template) on your ModelView class.

  3. Configure CSP Support with a Nonce Generator

    master

    To support Content Security Policy (CSP), pass a csp_nonce_generator function to the Admin constructor during initialization. This function must return a nonce that will be attached to all <script> and <style> resources. You are responsible for ensuring your Flask responses include the corresponding Content-Security-Policy header.

    When using Flask-Talisman, you can use its built-in generator via app.jinja_env.globals["csp_nonce"].

    app = Flask(__name__)
    
    talisman = Talisman(
        app,
        content_security_policy={
            "default-src": "'self'",
        },
        content_security_policy_nonce_in=["script-src", "style-src"]
    )
    csp_nonce_generator = app.jinja_env.globals["csp_nonce"]
    
    admin = admin.Admin(app, name="Example", theme=Bootstrap4Theme(), csp_nonce_generator=csp_nonce_generator)
  4. Enable Localization with Flask-Babel

    master

    Flask-Admin supports localization through Flask-Babel.

    1. Install Flask-Babel: pip install flask-babel.
    2. Define a locale selector function (e.g., reading from request.args or session).
    3. Initialize Babel with your Flask app and the selector function.

    Example implementation:

    from flask import Flask, request, session
    from flask_babel import Babel
    
    app = Flask(__name__)
    
    def get_locale():
        if request.args.get('lang'):
            session['lang'] = request.args.get('lang')
        return session.get('lang', 'en')
    
    babel = Babel(app, locale_selector=get_locale)
  5. Implement a custom database backend by extending BaseModelView

    master

    To use Flask-Admin with a non-standard database, extend flask_admin.model.BaseModelView. Your models must have a unique primary key (any type/name) and expose data via Python properties.

    When extending BaseModelView, you must implement several scaffolding methods to handle data access, display, and CRUD operations.

  6. Run a Flask-Admin example

    master

    Flask-Admin provides several usage examples in the /examples folder. The examples use uv to manage dependencies and the developer environment. To run an example (e.g., the SQLAlchemy example):

    1. Clone the repository.
    2. Navigate to the specific example directory.
    3. Run the application using uv run.
    4. Access the app at http://localhost:5000.
    git clone https://github.com/pallets-eco/flask-admin.git
    cd flask-admin/examples/sqla
    uv run main.py
  7. Generate URLs for views and records

    master

    Use Flask's url_for with a dot prefix to generate URLs for Flask-Admin views.

    • For ModelViews: Use the lowercase name of the model as the prefix (e.g., user.index_view).
    • For Standalone Views: Use the unique endpoint defined when adding the view (e.g., analytics.index).
    • For Specific Records: Pass the id and an optional url (for redirecting back).
  8. Group views in the admin menu

    master

    Organize your administrative views into categories and sub-categories in the sidebar menu.

    Menu Organization:

    • Categories: Pass a category string to admin.add_view() to group views under a top-level menu item.
    • Sub-categories: Use admin.add_sub_category(name='...', parent_name='...') to nest views within a category.
    • Links: Add arbitrary hyperlinks using admin.add_link(MenuLink(name='...', url='...', category='...')).
    • Dividers: Add menu dividers using admin.add_menu_item(MenuDivider(), target_category='...').
    admin.add_view(UserView(User, db.session, category="Team"))
    admin.add_view(ModelView(Role, db.session, category="Team"))
    admin.add_sub_category(name="Links", parent_name="Team")
    admin.add_link(MenuLink(name='Home Page', url='/', category='Links'))
    admin.add_menu_item(MenuDivider(), target_category='Links')