Home > Software design >  show images that are related to django model in admin
show images that are related to django model in admin

Time:10-29

I have a Book Model and BookImages model. Book is not related to Images directly ,instead BookImages has Book as foreign key and a Book can have many images. I want to show Book details along with images related to book in admin panel but here Book doesnt have any relation to BookImages. Instead BookImages points to Book Model. How can i show admin view with Book details and all Book Images.

Below is exact model code.

class Book(models.Model):
    name = models.CharField(max_length=100)
    description = models.CharField(max_length = 5000) 
    
class BookImage(models.Model):
    book = models.ForeignKey('Book', on_delete=models.CASCADE)
    image = models.ImageField(upload_to=settings.MEDIA_RELATIVE_ROOT   "/bookimages")

Python version is 3.7.12 and django version is 3.2.14

CodePudding user response:

Use TabularInline or StackedInline admin classes:

Example:

# admin.py

class BookImageInline(admin.TabularInline):
    model = BookImage
    fields = ['image']
    extra = 1


class BookAdmin(admin.ModelAdmin):
    inlines = [BookImageInline]
  • Related