pallets-eco / flask-admin

Simple and extensible administrative interface framework for Flask
https://flask-admin.readthedocs.io
BSD 3-Clause "New" or "Revised" License
5.8k stars 1.58k forks source link

add sqlmodel support #2528

Open whisper-bye opened 1 month ago

whisper-bye commented 1 month ago

as the title

samuelhwilliams commented 1 month ago

I agree that this feels like a useful addition. Happy to support a PR if anyone has the time to work on this.

whisper-bye commented 1 month ago

I gave it a quick try but was unable to create a user from the Web UI.

image

from sqlmodel import SQLModel, Field

class User(SQLModel, table=True):
    id: int | None = Field(default=None, primary_key=True)
    name: str
import logging

from flask import Flask, request, g
from flask_admin import Admin
from flask_admin.contrib.sqla import ModelView
from flask_admin.theme import Bootstrap4Theme
from flask_babel import Babel
from sqlalchemy import create_engine
from sqlmodel import SQLModel, Session

from models import User

app = Flask(__name__)
app.config["SECRET_KEY"] = "secret"

log = logging.getLogger('werkzeug')
log.setLevel(logging.ERROR)

def get_locale():
    user = getattr(g, "user", None)
    if user is not None:
        return user.locale
    return request.accept_languages.best_match(["en"])

def get_timezone():
    user = getattr(g, "user", None)
    if user is not None:
        return user.timezone

babel = Babel(app, locale_selector=get_locale, timezone_selector=get_timezone)

engine = create_engine("sqlite:///database.db", echo=True)
session = Session(engine)

admin = Admin(app, name="", theme=Bootstrap4Theme(swatch="simplex"))
admin.add_view(ModelView(User, session))

@app.route("/")
def index():
    return "<a href=\"/admin/\">Click me to get to Admin!</a>"

def create_db_and_tables():
    SQLModel.metadata.create_all(engine)

if __name__ == "__main__":
    create_db_and_tables()

    app.run()