【问题标题】:How to show two tables inline in django admin?如何在 django admin 中内联显示两个表?
【发布时间】:2021-06-18 10:12:49
【问题描述】:

我在 models.pyProductProductImage 中创建了两个模型。 产品 是展示特定产品所必需的。 ProductImage 用于显示一个产品的多张图片。

这是 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

这是 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)

我不断收到此错误:TypeError: 'MediaDefiningClass' object is not iterable 我搜索了这个错误,但我仍然没有设法解决这个问题。我还查看了文档 (https://docs.djangoproject.com/en/dev/ref/contrib/admin/#working-with-many-to-many-intermediary-models)

这个错误的原因是什么?

谢谢!

【问题讨论】:

    标签: django django-models django-rest-framework django-views django-forms


    【解决方案1】:

    admin.site.register(ProductAdmin, ProductImageAdmin) 你应该注册你的模型和 ProductAdmin 你不添加 ProductImageAdmin 所以用admin.site.register(Product, ProductAdmin)替换它

    【讨论】:

    • 谢谢先生。这就是问题所在。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-17
    • 2011-03-27
    • 1970-01-01
    • 2023-04-04
    • 2011-07-11
    相关资源
    最近更新 更多