Blerdijan Koliqi
Blerdijan Koliqi

Reputation: 27

How to show two tables inline in django admin?

I have created two models in models.py, Product and ProductImage. Product is needed to show a certain product. ProductImage is needed to show multiple images of one Product.

Here is the code in models.py :

class Product(models.Model):
    name = models.CharField(max_length=200, null=True)
    price = models.DecimalField(max_digits=7, decimal_places=2)
    digital = models.BooleanField(default=False, null=True, blank=False)
    image = models.ImageField(null=True, blank=True)

    def __str__(self):
        return self.name

    @property
    def imageURL(self):
        try:
            url = self.image.url
        except:
            url = ''
        return url 

class ProductImage(models.Model):
    product = models.ForeignKey(Product, default=None, on_delete=models.CASCADE)
    image = models.ImageField(null=True, blank=True)

    def __str__(self):
        return self.product.name
    
    @property
    def imageURL(self):
        try:
            url = self.image.url
        except:
            url = ''
        return url

And here is the code in admin.py :

from django.contrib import admin
from .models import *
# Register your models here.

class ProductImageAdmin(admin.TabularInline):
    model = ProductImage
    extra = 2 # how many rows to show

class ProductAdmin(admin.ModelAdmin):
    inlines = (ProductImageAdmin,)

admin.site.register(ProductAdmin, ProductImageAdmin)

I keep getting this error: TypeError: 'MediaDefiningClass' object is not iterable I searched this error but I still did not manage to fix this. I also looked in the documentation (https://docs.djangoproject.com/en/dev/ref/contrib/admin/#working-with-many-to-many-intermediary-models)

What is the cause of this error?

Thank you!

Upvotes: 1

Views: 1383

Answers (1)

seif
seif

Reputation: 295

In admin.site.register(ProductAdmin, ProductImageAdmin) you should register your model and ProductAdmin you don't add ProductImageAdmin so replace it with admin.site.register(Product, ProductAdmin)

Upvotes: 1

Related Questions