Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bug: default row actions (view, edit) don't work with custom ModelView #504

Closed
21Size opened this issue Feb 12, 2024 · 1 comment
Closed
Labels
bug Something isn't working

Comments

@21Size
Copy link

21Size commented Feb 12, 2024

Describe the bug
When i make custom ModelView from BaseModelView - view and edit buttons don't work. Links in buttons are broken like this http://127.0.0.1:8000/podruge-templates/undefined . But it works if i user 0.10.1 version

To Reproduce
`
class TemplatesView(BaseModelView):
db: AsyncIOMotorClient
project: ProjectNameEnum
identity: str
name: str
label: str
icon = "fa fa-blog"
pk_attr = "id"

sortable_fields = ["id"]
page_size = 100

fields = [
    StringField("id"),
    EnumField("service_name", required=True, enum=ServiceNameEnum, placeholder="Выберите сервис", label="Сервис"),
    IntegerField("pipeline_id", required=True, placeholder="ID воронки", label="ID воронки"),
    IntegerField("phone_field_id", required=True, placeholder="ID поля номера телефона",
                 label="ID поля номера телефона"),
    IntegerField("is_secondary_client_field_id", required=True, placeholder="ID поля вторички",
                 label="ID поля вторички"),
    MyListField(
        "Поля",
        CollectionField(
            "fields",
            required=False,
            fields=[
                StringField("source_field", required=True, placeholder="Текст в вопросе", label="Текст в вопросе"),
                IntegerField("amo_field_id", required=True, placeholder="ID поля в АМО", label="ID поля в АМО"),
                EnumField(
                    "amo_entity",
                    label="Сущность в АМО",
                    placeholder="Сущность в АМО",
                    enum=AmoEntityENum,
                    required=True,
                ),
                StringField("enum_code", label="enum_code", placeholder="enum_code", required=False),
            ],
        ),
    )
]

def __init__(self, project: ProjectNameEnum, name: str, label: str):
    super().__init__()
    self.identity = project.value
    self.name = name
    self.label = label
    self.project = project

    if project == ProjectNameEnum.podruge:
        self.db = db_client["clients"]
    elif project == ProjectNameEnum.at:
        self.db = db_client["at-clients"]
    elif project == ProjectNameEnum.zubareva:
        self.db = db_client["zub-clients"]

async def repr(self, obj: Any, request: Request) -> str:
    repr_method = getattr(
        obj,
        "__admin_repr__",
        lambda request: str(getattr(obj, self.pk_attr)),  # type: ignore[arg-type]
    )
    if inspect.iscoroutinefunction(repr_method):
        return await repr_method(request)
    return repr_method(request)

async def find_all(  # noqa: WPS211
    self,
    request: Request,
    skip: int = 0,
    limit: int = 100,
    where: Union[Dict[str, Any], str, None] = None,
    order_by: Optional[List[str]] = None,
) -> list[STemplateModel]:
    try:
        templates = await self.db.templates.find().to_list(length=100)
        return [STemplateModel(**x, id=str(x["_id"])) for x in templates]
    except ActionFailed as e:
        raise e
    except Exception as e:
        logger.error(traceback.format_exc())
        raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e))

async def count(self, request: Request, where: Union[Dict[str, Any], str, None] = None) -> int:
    return await self.db.templates.count_documents({})

async def find_by_pk(self, request: Request, pk: Any) -> STemplateModel | None:
    try:
        return await self.db.templates.find_one({"_id": pk})
    except ActionFailed as e:
        raise e
    except Exception as e:
        logger.error(traceback.format_exc())
        raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e))

async def find_by_pks(self, request: Request, pks: List[Any]) -> List[STemplateModel]:
    logger.info(f"Try to get categories by pks: {pks}")
    try:
        templates = await self.db.templates.find({"_on": {"_id": pks}}).to_list(length=100)
        logger.info(templates)
        return [STemplateModel(**x, id=str(x["_id"])) for x in templates]
    except ActionFailed as e:
        raise e
    except Exception as e:
        logger.error(traceback.format_exc())
        raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e))

`

Environment (please complete the following information):

  • Starlette-Admin version: [e.g. 0.13.2]
  • ORM/ODMs: No
@21Size 21Size added the bug Something isn't working label Feb 12, 2024
@hasansezertasan
Copy link
Contributor

If it's a custom backend you are using, you also should implement edit and delete logic.

Take a look at custom-backend example.

@jowilf jowilf closed this as completed Sep 30, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

3 participants