I’m working on an application with an admin interface, and I want to show the actual image rather than just its path in the admin page view. Below is my current code:
https://github.com/aminalaee/sqladmin
Title
How to Display the Actual Image Instead of Its Path on the Admin Page?
Description
I’m working on an application with an admin interface, and I want to show the actual image rather than just its path in the admin page view. Below is my current code:
Admin View
class PhotosAdmin(ModelView, model=Photos):
column_list = [
'id',
'application_id',
'url_photo',
]
can_delete = False
name = "Фотка"
name_plural = "Фотки"
icon = "fa-solid fa-camera"
Models
class Photos(Base):
"""Model representing a photo tied to an application."""
__tablename__ = 'photos'
id: Mapped[intpk]
application_id: Mapped[int] = mapped_column(
Integer,
ForeignKey('applications.id', ondelete="CASCADE"),
nullable=False
)
url_photo: Mapped[str] = mapped_column(String(255), nullable=False)
application: Mapped["Applications"] = relationship("Applications", back_populates="photos")
def __str__(self):
return f"Фотка {self.id}, {self.application_id}"
Router and Functions
async def save_photo(file: UploadFile, application_id: int):
file_location = f'app/static/images/{application_id}_{file.filename}'
with open(file_location, "wb+") as buffer:
shutil.copyfileobj(file.file, buffer)
photo = await PhotosDAO.add(
application_id=application_id,
url_photo=file_location
)
@router_application.post("/add/")
async def active_application(
name: Annotated[str, Form()],
phone_number: Annotated[str, Form()],
email: Annotated[str, Form()],
description: Annotated[str, Form()],
fileInputFirst: Annotated[UploadFile, File()],
fileInputSecond: Union[UploadFile, None] = None,
fileInputThird: Union[UploadFile, None] = None,
):
application = await ApplicationsDAO.add(
name=name,
phone_number=phone_number,
email=email,
description=description,
)
if application is None:
raise ApplicationCreateException
if fileInputFirst.filename.strip() != '':
await save_photo(fileInputFirst, application.id)
if fileInputSecond.filename.strip() != '':
await save_photo(fileInputSecond, application.id)
if fileInputThird.filename.strip() != '':
await save_photo(fileInputThird, application.id)
Question
How can I modify this setup so that the actual images appear in the admin interface instead of just the path?
So far, I’ve set up the admin view, models, and router functions as described above. The current configuration allows displaying the path to the image in the admin panel. However, I haven’t been able to display the actual image instead of the URL. I am looking for suggestions on how to modify the code or what properties to include to achieve this functionality.
rezuce is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.