""" Custom widgets for Django admin interface """ from django import forms from django.utils.html import format_html from django.utils.safestring import mark_safe from django.urls import reverse from django.conf import settings from ..models import ImageLibrary class ImageLibraryWidget(forms.Select): """Custom widget for selecting images from the library with visual preview""" def __init__(self, attrs=None): super().__init__(attrs) self.attrs.update( { "class": "image-library-select", "style": "display: none;", # Hide the original select } ) def render(self, name, value, attrs=None, renderer=None): """Render the widget with image previews""" # Get the original select element original_select = super().render(name, value, attrs, renderer) # Get all images from the library images = ImageLibrary.objects.all().order_by("-uploaded_at") # Create the visual interface html_parts = [ '
', original_select, # Keep the original select for form submission '
', ] # Add "No image" option no_image_selected = "selected" if not value else "" html_parts.append( f"""
No image
No image selected
""" ) # Add each image as an option for image in images: selected = "selected" if str(image.pk) == str(value) else "" image_url = image.image.url if image.image else "" # Use img tag for all images in widget to maintain clickability # SVG files will still display correctly with img tag preview_html = ( f'{image.alt_text}' ) html_parts.append( f"""
{preview_html}
{image.name} {image.get_category_display()} {image.width}x{image.height}
""" ) html_parts.extend( [ "
", "
", self._get_styles(), self._get_javascript(), ] ) return mark_safe("".join(html_parts)) def _get_styles(self): """Return CSS styles for the widget""" return """ """ def _get_javascript(self): """Return JavaScript for the widget functionality""" return """ """ class Media: css = { "all": ( "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css", ) }