GithubHelp home page GithubHelp logo

fastapi-admin / fastapi-admin Goto Github PK

View Code? Open in Web Editor NEW
2.6K 36.0 336.0 6.93 MB

A fast admin dashboard based on FastAPI and TortoiseORM with tabler ui, inspired by Django admin

Home Page: https://fastapi-admin-docs.long2ice.io

License: Apache License 2.0

Python 50.57% Makefile 0.65% Dockerfile 0.51% HTML 48.27%
fastapi admin-dashboard tortoise-orm tabler fastapi-admin admin dashboard

fastapi-admin's Introduction

FastAPI Admin

image image image image

中文文档 한국어 문서

Introduction

fastapi-admin is a fast admin dashboard based on FastAPI and TortoiseORM with tabler ui, inspired by Django admin.

Installation

> pip install fastapi-admin

Requirements

Online Demo

You can check a online demo here.

  • username: admin
  • password: 123456

Or pro version online demo here.

  • username: admin
  • password: 123456

Screenshots

Run examples in local

  1. Clone repo.

  2. Create .env file.

    DATABASE_URL=mysql://root:[email protected]:3306/fastapi-admin
    REDIS_URL=redis://localhost:6379/0
  3. Run docker-compose up -d --build.

  4. Visit http://localhost:8000/admin/init to create first admin.

Documentation

See documentation at https://fastapi-admin-docs.long2ice.io.

License

This project is licensed under the Apache-2.0 License.

fastapi-admin's People

Contributors

asedmammad avatar av1m avatar cvquez avatar fullonic avatar grski avatar kanikim avatar kozdincer avatar laggron42 avatar long2ice avatar oper18 avatar radiophysicist avatar swevm avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

fastapi-admin's Issues

404 not found

app = FastAPI()

register_tortoise(
    app,
    config={
        'connections': {
            'default': 'sqlite://database.sqlite',
        },
        'apps': {
            'models': {
                'models': ['fastapi_admin.models', 'models'],
                'default_connection': 'default',
            }
        }
    }, generate_schemas=True, add_exception_handlers=True,
)


@app.get("/")
def hello():
    return {"Hello": "World"}


app.mount('/admin', admin_app, 'admin_panel')


@app.on_event('startup')
async def startup():
    admin_app.init(
        admin_secret="test",
        permission=True,
        site=Site(
            name="FastAPI-Admin DEMO",
            login_footer="FASTAPI ADMIN - FastAPI Admin Dashboard",
            login_description="FastAPI Admin Dashboard",
            locale="en-US",
            locale_switcher=True,
            theme_switcher=True,
        ),
    )

I got 404 not found on host:port/admin
Thank you for help

windows 怎么办?

安装依赖时报错
RuntimeError: uvloop does not support Windows at the moment

admin/login POST does not work

Hello,
nice project and thanks for sharing.
I have successfully deployed and it seems everything is working.
I can use the followig command:

curl -X GET "http://192.168.1.75:8000/admin/site" -H "accept: application/json"

and get a proper result.
But if I use the following:

curl -X POST "http://192.168.1.75:8000/admin/login" -H "accept: application/json" -H "Content-Type: application/json" -d "{\"username\":\"marco\",\"password\":\"123456\"}"

I am getting:

{"msg":"Not Found"}

which I don't think it is correct.
In docker container "fastapi-admin" logs I am finding:

INFO: 192.168.1.111:41788 - "POST /admin/login HTTP/1.1" 404 Not Found

Visible data validation in frontend

Hi,

This is more of a conversation and you decide if this is the right place for it or not.
The rest-admin frontend support ways to visually highlight to a user what data in a form with fields are correct and not which is particularly useful at /login.

Default HttpException handler in FastApi do not return pure json which rest-admin expect in validation use cases but there is an easy way to achieve the same thing without raising an exception.
For example in async def login() one can do:

    usr_pwd_validation_error = {
        "name": "HttpException",
        "message": [{"field": "password", "message": "Incorrect password."}]
    }

    user = await get_object_or_404(user_model, username=login_in.username)
    if not user.is_active:
        raise HTTPException(status_code=HTTP_403_FORBIDDEN, detail="User is not Active!")
    if not pwd_context.verify(login_in.password, user.password):
        return JSONResponse(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, content=usr_pwd_validation_error)

Discussion point:
This won´t raise an exception per se but it return data to rest-admin a HttpException have occurred.
In your opinion is this the preferred way to feedback validation information to frontend or are there better ones?

Unable to create first admin

Hello, I'm try to use your admin panel but I have failed. When i try to register first user admin/init (input name and password) but I've got error: File "/usr/local/lib/python3.8/site-packages/tortoise/fields/base.py", line 216, in validate raise ValidationError(f"{self.model_field_name}: {exc}") tortoise.exceptions.ValidationError: email: Value must not be None. I don't have any email input. Can you help me?

"db: Session = next(get_db())):" is only used one time?

Hi. Let me first clarify this: I know the difference between using: "db: Session = Depends(get_db)):" and using ""db: Session = next(get_db())):".

Now over to the problem:

I have a local function inside my code which is suppose to grab data from db, it works for checking if something exist or not, but i am not able to grab the actual data?

here is my DB code:

from fastapi import FastAPI, WebSocket,   HTTPException, Depends
from fastapi.responses import HTMLResponse
from fastapi.middleware.cors import CORSMiddleware
from .websocket_manager import html
from starlette.websockets import WebSocketDisconnect
import json

from fastapi_websocket import models, schemas, crud, algorithms
from sqlalchemy.orm import Session

#from .algorithms import *
from .database import SessionLocal, engine

models.Base.metadata.create_all(bind=engine)

app = FastAPI()


app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["*"],
    allow_headers=["*"],
    allow_credentials=True,
)


# Dependency
def get_db():
    try:
        db = SessionLocal()
        yield db
    finally:

here is the function:

#this function runs inside algorithm.py
async def run_multiple_queries(exercise_ID, user_ID, db: Session = next(get_db())):
    db_exercise = crud.check_if_woit_sense_or_woit_track(db, exercise_id=exercise_ID)

    if not db_exercise:
        await connection_manager.send_message_to_user("Sorry, the exercise you subscribed does not exists, support team is working on it!", user_ID)
    elif db_exercise:

        await connection_manager.send_message_to_user("NICEEEEE", user_ID)
        print(db_exercise)  # prints the object
        for info in db_exercise:
            print(info.user_ID)  # doesnt print anything..

I am able to run the "IF" to check if "exercise_ID" is in that table or not, but other than this doesnt work.

For instance, i have this function in another project which works perfectly using "next":


#this is run inside main.py, works perfectly
def auto_generate_plan_tasks(user_ID: int, program_ID: int, db:Session= next(get_db())):  # works perfectly
    db_program_tasks = crud.get_program_tasks_by_program_ID(db, program_id=program_ID)
    if db_program_tasks is None:
        raise HTTPException(status_code=404, detail="finner ingenting ?")
    for details in db_program_tasks:
        crud.insert_workout_plan_tasks(db, user_id=user_ID, program_tasks_id=details.program_tasks_ID, day_to_perform_the_task=calendar.day_name[details.day_number_to_perform_task])
    return db_program_tasks

anyone knows that the issue is? Why does this function above work inside main.by on project2 but the first function mentioed does not work?

ImportError: cannot import name 'Model' from 'tortoise' (/usr/local/lib/python3.9/site-packages/tortoise/__init__.py)

Hi!
Problem with deploy in docker container.

File "./app/main.py", line 21, in
api_1 | from fastapi_admin.depends import get_model
api_1 | File "/usr/local/lib/python3.9/site-packages/fastapi_admin/init.py", line 1, in
api_1 | from . import routes # noqa: F401
api_1 | File "/usr/local/lib/python3.9/site-packages/fastapi_admin/routes/init.py", line 3, in
api_1 | from ..depends import jwt_required
api_1 | File "/usr/local/lib/python3.9/site-packages/fastapi_admin/depends.py", line 12, in
api_1 | from .factory import app
api_1 | File "/usr/local/lib/python3.9/site-packages/fastapi_admin/factory.py", line 6, in
api_1 | from tortoise import Model
api_1 | ImportError: cannot import name 'Model' from 'tortoise' (/usr/local/lib/python3.9/site-packages/tortoise/init.py)

How solve this problem?

admin app not loading properly

When using the sample code, /admin returns 404.

Here's my main.py:

from fastapi import FastAPI
from fastapi_admin.factory import app as admin_app
from fastapi_admin.site import Site
from starlette.middleware.cors import CORSMiddleware
from tortoise.contrib.fastapi import register_tortoise

app = FastAPI()


@app.get("/")
async def root():
    return {"message": "Hello World"}

app.add_middleware(
        CORSMiddleware,
        allow_origins=["*"],
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
        expose_headers=["*"],
    )
register_tortoise(
    app,
    db_url="sqlite://:memory:",
    modules={"models": ["database.models"]},
    generate_schemas=True,
    add_exception_handlers=True,
)

app.mount("/admin", admin_app)

@app.on_event('startup')
async def startup():
    await admin_app.init(
        admin_secret="test",
        site=Site(
            name="FastAPI-Admin DEMO",
            login_footer="FASTAPI ADMIN - FastAPI Admin Dashboard",
            login_description="FastAPI Admin Dashboard",
            locale="en-US",
            locale_switcher=True,
            theme_switcher=True,
        ),
    )

Here's my requirements.txt:

aiomysql==0.0.21
aiosqlite==0.16.0
asyncpg==0.22.0
bcrypt==3.2.0
cffi==1.14.5
click==7.1.2
colorama==0.4.4
fastapi==0.63.0
fastapi-admin==0.3.3
gunicorn==20.1.0
h11==0.12.0
iso8601==0.1.14
Jinja2==2.11.3
MarkupSafe==1.1.1
passlib==1.7.4
prompt-toolkit==3.0.18
pycparser==2.20
pydantic==1.8.1
PyJWT==2.1.0
PyMySQL==0.9.3
pypika-tortoise==0.1.0
python-dotenv==0.17.1
python-rapidjson==1.0
pytz==2020.5
six==1.15.0
starlette==0.13.6
tortoise-orm==0.17.2
typing-extensions==3.10.0.0
uvicorn==0.13.4
wcwidth==0.2.5
XlsxWriter==1.4.0

Issue with resource resolving.

Hi!

There are some unobvious thing with getting Tortose model in the fastapi_admin.depends:

def get_model(resource: Optional[str] = Path(...)):
    if not resource:
        return
    for app, models in Tortoise.apps.items():
        model = models.get(resource.title())
        if model:
            return model

In the models variable a keys in case sensitive. And get model with word capitalization. So if a model name will consist of two and more words (in CamelCase) then this resource will not found.

Example:
models has keys 'Admin', 'BugReport'. But in resource arg will be 'bugreport'.

Maybe need add to the documentation this restriction description or fix get_model function?

As variant of solution I can suggest following:

def get_model(resource: Optional[str] = Path(...)):
    if not resource:
        return
    for app, models in Tortoise.apps.items():
        models = {key.lower(): val for key, val in models.items()}
        
        model = models.get(resource.title())
        if model:
            return model

Not working /admin/init

Hi! I've this error when trying to load /admin/init:

ERROR:uvicorn.error:Exception in ASGI application
Traceback (most recent call last):
  File "/usr/local/lib/python3.9/site-packages/uvicorn/protocols/http/httptools_impl.py", line 398, in run_asgi
    result = await app(self.scope, self.receive, self.send)
  File "/usr/local/lib/python3.9/site-packages/uvicorn/middleware/proxy_headers.py", line 45, in __call__
    return await self.app(scope, receive, send)
  File "/usr/local/lib/python3.9/site-packages/uvicorn/middleware/debug.py", line 81, in __call__
    raise exc from None
  File "/usr/local/lib/python3.9/site-packages/uvicorn/middleware/debug.py", line 78, in __call__
    await self.app(scope, receive, inner_send)
  File "/usr/local/lib/python3.9/site-packages/fastapi/applications.py", line 199, in __call__
    await super().__call__(scope, receive, send)
  File "/usr/local/lib/python3.9/site-packages/starlette/applications.py", line 112, in __call__
    await self.middleware_stack(scope, receive, send)
  File "/usr/local/lib/python3.9/site-packages/starlette/middleware/errors.py", line 181, in __call__
    raise exc from None
  File "/usr/local/lib/python3.9/site-packages/starlette/middleware/errors.py", line 159, in __call__
    await self.app(scope, receive, _send)
  File "/usr/local/lib/python3.9/site-packages/starlette/middleware/base.py", line 26, in __call__
    await response(scope, receive, send)
  File "/usr/local/lib/python3.9/site-packages/starlette/responses.py", line 224, in __call__
    await run_until_first_complete(
  File "/usr/local/lib/python3.9/site-packages/starlette/concurrency.py", line 24, in run_until_first_complete
    [task.result() for task in done]
  File "/usr/local/lib/python3.9/site-packages/starlette/concurrency.py", line 24, in <listcomp>
    [task.result() for task in done]
  File "/usr/local/lib/python3.9/site-packages/starlette/responses.py", line 216, in stream_response
    async for chunk in self.body_iterator:
  File "/usr/local/lib/python3.9/site-packages/starlette/middleware/base.py", line 56, in body_stream
    task.result()
  File "/usr/local/lib/python3.9/site-packages/starlette/middleware/base.py", line 38, in coro
    await self.app(scope, receive, send)
  File "/usr/local/lib/python3.9/site-packages/starlette/middleware/cors.py", line 78, in __call__
    await self.app(scope, receive, send)
  File "/usr/local/lib/python3.9/site-packages/starlette/middleware/base.py", line 26, in __call__
    await response(scope, receive, send)
  File "/usr/local/lib/python3.9/site-packages/starlette/responses.py", line 224, in __call__
    await run_until_first_complete(
  File "/usr/local/lib/python3.9/site-packages/starlette/concurrency.py", line 24, in run_until_first_complete
    [task.result() for task in done]
  File "/usr/local/lib/python3.9/site-packages/starlette/concurrency.py", line 24, in <listcomp>
    [task.result() for task in done]
  File "/usr/local/lib/python3.9/site-packages/starlette/responses.py", line 216, in stream_response
    async for chunk in self.body_iterator:
  File "/usr/local/lib/python3.9/site-packages/starlette/middleware/base.py", line 56, in body_stream
    task.result()
  File "/usr/local/lib/python3.9/site-packages/starlette/middleware/base.py", line 38, in coro
    await self.app(scope, receive, send)
  File "/usr/local/lib/python3.9/site-packages/starlette/middleware/base.py", line 26, in __call__
    await response(scope, receive, send)
  File "/usr/local/lib/python3.9/site-packages/starlette/responses.py", line 224, in __call__
    await run_until_first_complete(
  File "/usr/local/lib/python3.9/site-packages/starlette/concurrency.py", line 24, in run_until_first_complete
    [task.result() for task in done]
  File "/usr/local/lib/python3.9/site-packages/starlette/concurrency.py", line 24, in <listcomp>
    [task.result() for task in done]
  File "/usr/local/lib/python3.9/site-packages/starlette/responses.py", line 216, in stream_response
    async for chunk in self.body_iterator:
  File "/usr/local/lib/python3.9/site-packages/starlette/middleware/base.py", line 56, in body_stream
    task.result()
  File "/usr/local/lib/python3.9/site-packages/starlette/middleware/base.py", line 38, in coro
    await self.app(scope, receive, send)
  File "/usr/local/lib/python3.9/site-packages/starlette/middleware/base.py", line 26, in __call__
    await response(scope, receive, send)
  File "/usr/local/lib/python3.9/site-packages/starlette/responses.py", line 224, in __call__
    await run_until_first_complete(
  File "/usr/local/lib/python3.9/site-packages/starlette/concurrency.py", line 24, in run_until_first_complete
    [task.result() for task in done]
  File "/usr/local/lib/python3.9/site-packages/starlette/concurrency.py", line 24, in <listcomp>
    [task.result() for task in done]
  File "/usr/local/lib/python3.9/site-packages/starlette/responses.py", line 216, in stream_response
    async for chunk in self.body_iterator:
  File "/usr/local/lib/python3.9/site-packages/starlette/middleware/base.py", line 56, in body_stream
    task.result()
  File "/usr/local/lib/python3.9/site-packages/starlette/middleware/base.py", line 38, in coro
    await self.app(scope, receive, send)
  File "/usr/local/lib/python3.9/site-packages/starlette/exceptions.py", line 82, in __call__
    raise exc from None
  File "/usr/local/lib/python3.9/site-packages/starlette/exceptions.py", line 71, in __call__
    await self.app(scope, receive, sender)
  File "/usr/local/lib/python3.9/site-packages/starlette/routing.py", line 580, in __call__
    await route.handle(scope, receive, send)
  File "/usr/local/lib/python3.9/site-packages/starlette/routing.py", line 390, in handle
    await self.app(scope, receive, send)
  File "/usr/local/lib/python3.9/site-packages/fastapi/applications.py", line 199, in __call__
    await super().__call__(scope, receive, send)
  File "/usr/local/lib/python3.9/site-packages/starlette/applications.py", line 112, in __call__
    await self.middleware_stack(scope, receive, send)
  File "/usr/local/lib/python3.9/site-packages/starlette/middleware/errors.py", line 181, in __call__
    raise exc from None
  File "/usr/local/lib/python3.9/site-packages/starlette/middleware/errors.py", line 159, in __call__
    await self.app(scope, receive, _send)
  File "/usr/local/lib/python3.9/site-packages/starlette/middleware/base.py", line 25, in __call__
    response = await self.dispatch_func(request, self.call_next)
  File "/usr/local/lib/python3.9/site-packages/fastapi_admin/providers/login.py", line 132, in authenticate
    response = await call_next(request)
  File "/usr/local/lib/python3.9/site-packages/starlette/middleware/base.py", line 45, in call_next
    task.result()
  File "/usr/local/lib/python3.9/site-packages/starlette/middleware/base.py", line 38, in coro
    await self.app(scope, receive, send)
  File "/usr/local/lib/python3.9/site-packages/starlette/middleware/base.py", line 25, in __call__
    response = await self.dispatch_func(request, self.call_next)
  File "/usr/local/lib/python3.9/site-packages/fastapi_admin/middlewares.py", line 19, in language_processor
    response = await call_next(request)
  File "/usr/local/lib/python3.9/site-packages/starlette/middleware/base.py", line 45, in call_next
    task.result()
  File "/usr/local/lib/python3.9/site-packages/starlette/middleware/base.py", line 38, in coro
    await self.app(scope, receive, send)
  File "/usr/local/lib/python3.9/site-packages/starlette/exceptions.py", line 82, in __call__
    raise exc from None
  File "/usr/local/lib/python3.9/site-packages/starlette/exceptions.py", line 71, in __call__
    await self.app(scope, receive, sender)
  File "/usr/local/lib/python3.9/site-packages/starlette/routing.py", line 580, in __call__
    await route.handle(scope, receive, send)
  File "/usr/local/lib/python3.9/site-packages/starlette/routing.py", line 241, in handle
    await self.app(scope, receive, send)
  File "/usr/local/lib/python3.9/site-packages/starlette/routing.py", line 52, in app
    response = await func(request)
  File "/usr/local/lib/python3.9/site-packages/fastapi/routing.py", line 201, in app
    raw_response = await run_endpoint_function(
  File "/usr/local/lib/python3.9/site-packages/fastapi/routing.py", line 148, in run_endpoint_function
    return await dependant.call(**values)
  File "/usr/local/lib/python3.9/site-packages/fastapi_admin/providers/login.py", line 149, in init_view
    return templates.TemplateResponse("init.html", context={"request": request})
  File "/usr/local/lib/python3.9/site-packages/starlette/templating.py", line 80, in TemplateResponse
    template = self.get_template(name)
  File "/usr/local/lib/python3.9/site-packages/starlette/templating.py", line 67, in get_template
    return self.env.get_template(name)
  File "/usr/local/lib/python3.9/site-packages/jinja2/environment.py", line 997, in get_template
    return self._load_template(name, globals)
  File "/usr/local/lib/python3.9/site-packages/jinja2/environment.py", line 958, in _load_template
    template = self.loader.load(self, name, self.make_globals(globals))
  File "/usr/local/lib/python3.9/site-packages/jinja2/loaders.py", line 125, in load
    source, filename, uptodate = self.get_source(environment, name)
  File "/usr/local/lib/python3.9/site-packages/jinja2/loaders.py", line 214, in get_source
    raise TemplateNotFound(template)
jinja2.exceptions.TemplateNotFound: init.html

My requirements.txt:

aerich==0.5.3
aiofiles==0.7.0
aioredis==1.3.1
asgi-lifespan==1.0.1
asgi-testclient==0.3.1
asyncpg==0.23.0
elastic-apm==6.2.0
factory-boy==3.2.0
Faker==8.4.0
fastapi==0.65.1
fastapi-admin==1.0.0
flake8==3.9.2
httpx==0.18.1
isort==5.8.0
JSON-log-formatter==0.3.1
mypy==0.812
mypy-extensions==0.4.3
psycopg2==2.8.6
pydantic==1.8.2
pytest==6.2.4
pytest-asyncio==0.15.1
starlette==0.14.2
starlette-prometheus==0.7.0
tortoise-orm==0.17.3
uvicorn==0.13.4
uvloop==0.15.2

As you can see, I'm using latest version of fastapi_admin (1.0.0)

I just going to fastapi_admin source code and not found 'init.html' file in the templates directory.
In the docs there are no any information regarding this case.

Should I add my own init.html template file?
And what there should be? What there should happen at all?
BTW, I'have same issue with getting 404 on /admin path.
So I suppose that it associate with first admin init (/admin/init). But unfortunately i getting 500 on it.

Could you please help me with it?

PS.: sorry for my english.

Getting the error cannot import name 'Model' from 'tortoise'

I'm a beginner in fastAPI.I thought it would be easier for me than Django. But, I'm really stuck on this issue.Please help me to fix this .
File "c:\users\suhail\appdata\local\programs\python\python39-32\lib\multiprocessing\process.py", line 315, in _bootstrap
self.run()
File "c:\users\suhail\appdata\local\programs\python\python39-32\lib\multiprocessing\process.py", line 108, in run
self._target(*self._args, **self.kwargs)
File "c:\users\suhail\appdata\local\programs\python\python39-32\lib\site-packages\uvicorn\subprocess.py", line 61, in subprocess_started
target(sockets=sockets)
File "c:\users\suhail\appdata\local\programs\python\python39-32\lib\site-packages\uvicorn\server.py", line 48, in run
loop.run_until_complete(self.serve(sockets=sockets))
File "c:\users\suhail\appdata\local\programs\python\python39-32\lib\asyncio\base_events.py", line 642, in run_until_complete
return future.result()
File "c:\users\suhail\appdata\local\programs\python\python39-32\lib\site-packages\uvicorn\server.py", line 55, in serve
config.load()
File "c:\users\suhail\appdata\local\programs\python\python39-32\lib\site-packages\uvicorn\config.py", line 308, in load
self.loaded_app = import_from_string(self.app)
File "c:\users\suhail\appdata\local\programs\python\python39-32\lib\site-packages\uvicorn\importer.py", line 23, in import_from_string
raise exc from None
File "c:\users\suhail\appdata\local\programs\python\python39-32\lib\site-packages\uvicorn\importer.py", line 20, in import_from_string
module = importlib.import_module(module_str)
File "c:\users\suhail\appdata\local\programs\python\python39-32\lib\importlib_init
.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "", line 1030, in _gcd_import
File "", line 1007, in _find_and_load
File "", line 986, in find_and_load_unlocked
File "", line 680, in load_unlocked
File "", line 790, in exec_module
File "", line 228, in call_with_frames_removed
File ".\main.py", line 7, in
from fastapi_admin.factory import app as admin_app
File "c:\users\suhail\appdata\local\programs\python\python39-32\lib\site-packages\fastapi_admin_init
.py", line 1, in
from . import routes # noqa: F401
File "c:\users\suhail\appdata\local\programs\python\python39-32\lib\site-packages\fastapi_admin\routes_init
.py", line 3, in
from ..depends import jwt_required
File "c:\users\suhail\appdata\local\programs\python\python39-32\lib\site-packages\fastapi_admin\depends.py", line 12, in
from .factory import app
File "c:\users\suhail\appdata\local\programs\python\python39-32\lib\site-packages\fastapi_admin\factory.py", line 6, in
from tortoise import Model
ImportError: cannot import name 'Model' from 'tortoise' (c:\users\suhail\appdata\local\programs\python\python39-32\lib\site-packages\tortoise_
init.py)

[QUESTION] Creating superuser ?

Could you please give me and example for creating a superuser ? ...reading the docs I think is by console. But how can I use the command fastapi-admin ?...console says "command not found"

PK values only integer

Hi! It's me again))

Could you please replace type annotation for pk path params in the admin routes with Union[int, UUID]?

It would allow to use UUID type for primary keys.

基于权限的页面显示

根据用户权限显示不同的页面和页面按钮,根据后端路由自动生成Menu结构,而不用手动配置。用户login登录成功的时候,返回该用户拥有的权限,然后根据权限渲染页面

NoSQL db support

Hello, I am using both PostgreSQL and MongoDB on my fastapi project.
Is there any possibility to add Mongodb collections to admin dashboard and enable CRUD operations for them as well?

本地启动examble报错:/bin/sh -c mkdir -p /fastapi-admin

ERROR: Service 'app' failed to build: The command '/bin/sh -c mkdir -p /fastapi-admin' returned a non-zero code: 1 抛开权限不说,这里既然用了-c是不是应该把后面的mkdir及其参数用引号包裹起来?
/bin/sh -c 'mkdir -p /fastapi-admin'
我该如何修改启动脚本?

权限问题,我手动创建了/fastapi-admin,并把文件夹属主改为了当前用户

静态文件重复加载问题

每次切换标签似乎所有的js css文件都要请求一遍
这个方便优化吗
还有一个是国内用户建议使用unpkg的国内镜像
unpkg.zhimg.com

我看issues还是有挺多国人的

Uvloop dependency

Hi, I discovered this fantastic project of yours, and would like to use it in my project. However, when I try to install fastapi-admin, I discovered that uvloop is a required dependency. As I understand, it is better to use uvloop with FastAPI, however uvloop is not available on windows, so it would be better, if possible, to remove uvloop from the required dependencies. Since I am using windows as my dev machine, I would appreciate it if this could be changed.

Backend Integration

下面这段不能执行

from fastapi_admin.factory import app as admin_app

fast_app = FastAPI()

register_tortoise(fast_app, config=TORTOISE_ORM, generate_schemas=True)

fast_app.mount('/admin', admin_app)

@fast_app.on_event('startup')
async def startup():
    await admin_app.init(
        admin_secret="test",
        permission=True,
        site=Site(
            name="FastAPI-Admin DEMO",
            login_footer="FASTAPI ADMIN - FastAPI Admin Dashboard",
            login_description="FastAPI Admin Dashboard",
            locale="en-US",
            locale_switcher=True,
            theme_switcher=True,
        ),
    )

can´t find setup.py

Hi Sir,
I don´t understand step 3 of that local example. There is no setup.py, the command "python setup.py install" fails.

facing issue in running docker

Dear Sir,

File "uvloop/loop.pyx", line 1994, in uvloop.loop.Loop.create_connection
app_1 | ConnectionRefusedError: [Errno 111] Connection refused
app_1 |
app_1 | ERROR: Application startup failed. Exiting.
app_1 | INFO: Started server process [1]
app_1 | INFO: Waiting for application startup.
app_1 | ERROR: Traceback (most recent call last):
app_1 | File "/usr/local/lib/python3.9/site-packages/starlette/routing.py", line 526, in lifespan
app_1 | async for item in self.lifespan_context(app):
app_1 | File "/usr/local/lib/python3.9/site-packages/starlette/routing.py", line 467, in default_lifespan
app_1 | await self.startup()
app_1 | File "/usr/local/lib/python3.9/site-packages/starlette/routing.py", line 502, in startup
app_1 | await handler()
app_1 | File "./examples/main.py", line 34, in startup
app_1 | redis = await aioredis.create_redis_pool("redis://localhost", encoding="utf8")
app_1 | File "/usr/local/lib/python3.9/site-packages/aioredis/commands/init.py", line 188, in create_redis_pool
app_1 | pool = await create_pool(address, db=db,
app_1 | File "/usr/local/lib/python3.9/site-packages/aioredis/pool.py", line 58, in create_pool
app_1 | await pool._fill_free(override_min=False)
app_1 | File "/usr/local/lib/python3.9/site-packages/aioredis/pool.py", line 383, in _fill_free
app_1 | conn = await self._create_new_connection(self._address)
app_1 | File "/usr/local/lib/python3.9/site-packages/aioredis/connection.py", line 111, in create_connection
app_1 | reader, writer = await asyncio.wait_for(open_connection(
app_1 | File "/usr/local/lib/python3.9/asyncio/tasks.py", line 442, in wait_for
app_1 | return await fut
app_1 | File "/usr/local/lib/python3.9/site-packages/aioredis/stream.py", line 23, in open_connection
app_1 | transport, _ = await get_event_loop().create_connection(
app_1 | File "uvloop/loop.pyx", line 2017, in create_connection
app_1 | File "uvloop/loop.pyx", line 1994, in uvloop.loop.Loop.create_connection
app_1 | ConnectionRefusedError: [Errno 111] Connection refused
app_1 |
app_1 | ERROR: Application startup failed. Exiting.
fastapi-admin_app_1 exited with code 0
(testpy3.9) iibadmin@iibadmin-uat-ubuntu:~/Python-3.9.1/fastapi-admin$ sudo docker-comp

Error on TortoiseORM start

I'm getting an error when first booting up my app after migrations and upgrades: tortoise.exceptions.ConfigurationError: backward relation "adminlogs" duplicates in model User

FastAPI Admin v0.3.3

Here is my models.py for reference:

from tortoise import fields, models
from tortoise.contrib.pydantic import pydantic_model_creator
from fastapi_admin.models import AbstractUser, AbstractPermission, AbstractRole, AbstractAdminLog
from pydantic import BaseModel

class User(AbstractUser):
    id = fields.BigIntField(pk=True)
    email = fields.CharField(unique=True, max_length=100)
    first_name = fields.CharField(unique=True, max_length=100)
    last_name = fields.CharField(unique=True, max_length=100)
    created_at = fields.DatetimeField(auto_now_add=True)
    updated_at = fields.DatetimeField(auto_now=True)
    profile_url = fields.TextField()
    description = fields.TextField(null=True)
    is_tutor = fields.BooleanField(default=False)
    password = fields.CharField(
        max_length=200, description="Will auto hash with raw password when change", null=True
    )

    creds : fields.OneToOneRelation["Credentials"]

    def __str__(self):
        return f"{self.first_name} {self.last_name}"

    class PydanticMeta:
        exclude = ['password', 'username']

class Permission(AbstractPermission):
    """
    must inheritance AbstractPermission
    """
    pass

class Role(AbstractRole):
    """
    must inheritance AbstractRole
    """
    pass


class AdminLog(AbstractAdminLog):
    """
    must inheritance AbstractAdminLog
    """
    pass


class Credentials(models.Model):
    id = fields.BigIntField(pk=True)
    json_field = fields.JSONField()
    user = fields.OneToOneField("models.User", related_name="creds")

大哥,搜索怎么定义

文档中:
搜索
定义 menu.search_fields会渲染出一个搜索框。

Xlsx 导出
FastAPI-admin 可导出 xlsx 文件,只需在menu设置export=True。

代码中 需要怎么定义?
menu = Menu(
...
search_field="",
export=True,
)
我这样写不行

docker-compose with error

when running with docker compose, an error occur:

api_1 | INFO:uvicorn.error:Application startup complete.

在example/main.py中增加了一个 Menu,如何才能在前端显示

1.在models.py中追加了 class Order的定义;数据库中通过sql创建了Order表。
2.在main.py中追加了如下的部分
Menu(
name="Order",
url="/rest/Order",
icon="fa fa-gear",
import_=True,
search_fields=("userid",),
),
3.重新打包了 docker-compose up -d --build
4.前端也重新 build了

反复刷新,前端都不能看见 Order节点。 特意去掉了 Config Menu,从前端确实看不见了。

docker image

docker image fastapi-admin cannot start. no error log.

Example - 404 Error

Hi, before integrating your solution into my project, I tried to execute your example :

image

The application start well :

image

And the data are injected into the database :

image

But when I try to navigate to 127.0.0.1:8000/admin, I have an 404 error :

image

image

Otherwise, 127.0.0.1:8000/admin/docs works

My configuration :

  • os: Ubuntu 18.04
  • docker: 19.03.13
  • docker-compose: 1.26.0

If you need more informations, do not hesitate to ask me.

Thank you !

修改用户时间问题

修改用户信息的时候,时间字段出现错误。
tortoise.exceptions.OperationalError: (1292, "Incorrect datetime value: '2021-01-13T00:00:00+00:00' for column 'last_login' at row 1")

No model with name 'User' registered in app 'diff_models'

After installing (from the dev branch) and setting up fastapi-admin, I attempted to run aerich migrate, which failed with the error:

tortoise.exceptions.ConfigurationError: No model with name 'User' registered in app 'diff_models'.

But I didn't register any app named diff_models, and I don't see it in the code for this repo... so I'm pretty stumped as to how to fix this. If you could please point me in the right direction, that would be amazing.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.