from django.contrib import admin from .models import Plant, PlantImage # Inline class for handling images class PlantImageInline(admin.TabularInline): model = PlantImage extra = 3 # Display three empty forms for adding new images fields = ('image',) # Only include fields that exist on PlantImage can_delete = True # Allow deletion of images max_num = 10 # Limit to 10 images per plant (optional) @admin.register(Plant) class PlantAdmin(admin.ModelAdmin): list_display = ('id', 'name', 'description', 'get_images', 'buy_price', 'sell_price', 'stock') search_fields = ('name','description') # Add search functionality inlines = [PlantImageInline] # Add inline editing for images def save_related(self, request, form, formsets, change): super().save_related(request, form, formsets, change) # Ensure all related PlantImage objects are saved correctly for formset in formsets: if hasattr(formset, 'save'): formset.save() def get_images(self, obj): """Display the first image or a placeholder in the list view.""" images = obj.images.all() # Access related images via the 'images' related_name if images.exists(): return images[0].image.url # Show URL of the first image return "No Images" get_images.short_description = "Images" # Header for the admin column