简体   繁体   English

如何在 django 管理员中内联显示两个表?

[英]How to show two tables inline in django admin?

I have created two models in models.py , Product and ProductImage .我在models.pyProductProductImage中创建了两个模型。 Product is needed to show a certain product.需要产品来展示某个产品。 ProductImage is needed to show multiple images of one Product.需要ProductImage来显示一个产品的多个图像。

Here is the code in models.py :这是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 :这是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.我不断收到此错误: TypeError: 'MediaDefiningClass' object is not iterable我搜索了此错误,但我仍然无法解决此问题。 I also looked in the documentation ( https://docs.djangoproject.com/en/dev/ref/contrib/admin/#working-with-many-to-many-intermediary-models )我还查看了文档( 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!谢谢!

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)admin.site.register(ProductAdmin, ProductImageAdmin)你应该注册你的 model 和 ProductAdmin 你不添加 ProductImageAdmin 所以用admin.site.register(Product, ProductAdmin)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM