simple-plant-archive-django/plant_catalog/catalog/admin.py

34 lines
1.4 KiB
Python
Raw Permalink Normal View History

2024-10-05 17:30:35 +02:00
from django.contrib import admin
2025-03-02 10:43:19 +01:00
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)
2024-10-05 17:30:35 +02:00
@admin.register(Plant)
class PlantAdmin(admin.ModelAdmin):
2025-03-02 10:43:19 +01:00
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