【问题标题】:How can I add a related object to the Admin index view?如何将相关对象添加到管理索引视图?
【发布时间】:2009-09-22 21:46:31
【问题描述】:

我希望能够显示图像是否与 list_display 视图中的每个产品相关联。 我似乎遇到了麻烦,因为我正在处理一个关联的对象。

models.py

class ImageMain(models.Model):
    """This is the Main Image of the product"""
    product = models.ForeignKey(Product)
    photo = models.ImageField(upload_to='lcdtvs')  
    pub_date = models.DateTimeField('date published', auto_now_add=True)

class Product(models.Model):
   name = models.CharField(max_length=100)
   poll = models.ForeignKey(Poll)
   pub_date = models.DateTimeField('date published', auto_now_add=True)
   size = models.IntegerField(default=0)

admin.py

def photo_for_product(obj):
    images = obj.imagemain_set.all()
    return images[0].photo

class ProductAdmin(admin.ModelAdmin):
   list_display = ('name', "photo_for_product")
   inlines = [DescriptionInline, FeatureInline, AffiliateInline]

   def upper_case_name(self, obj):
       return ("%s" % (obj.name)).upper()

   def photo_for_product(self, obj):
       images = self.imagemain_set.all()
       return images[0].photo

admin.site.register(ImageMain)
admin.site.register(Product, ProductAdmin)

由于某种原因,upper_case_name() 在列表视图中显示正常。 photo_for_product() 只是一直显示(无)。

我也尝试在 photo_for_product 方法中使用 pdb,但 Django 不喜欢那样。

我也尝试将 callable 放在 ModelAdmin 方法之前,但是这会产生很多错误:

ProductAdmin.list_display[1], 'photo_for_product' is not a callable or an attribute of 'ProductAdmin' or found in the model 'Product'.

【问题讨论】:

    标签: django django-admin


    【解决方案1】:

    从您的问题中不清楚您希望输出是什么。您说您想知道“是否已关联图像” - 如果是这样,您可以试试这个:

    def photo_for_product(self, obj):
        images = self.imagemain_set.all()
        if images:
            return True
        else:
            return False
    photo_for_product.boolean = True
    

    如果你想真正看到图像,你需要返回一些 HTML,在 img 标签中呈现它。

    def photo_for_product(self, obj):
        images = self.imagemain_set.all()
        if images:
            return '<img src="%s">' % images[0].photo.url
        else:
            return ''
    photo_for_product.allow_tags = True
    

    【讨论】:

    • 我希望输出是图像路径的字符串。显然,问题在于 images[0].photo 是 ImageFieldFile 而不是字符串。
    【解决方案2】:

    编写一个以字符串形式返回必要信息的方法,并将该方法的名称添加到您的管理类的 list_displays 中。

    【讨论】:

      【解决方案3】:

      我希望输出是图像路径的字符串。显然,问题在于 images[0].photo 是 ImageFieldFile 而不是字符串。

      似乎默认情况下,ImageFieldFile 具有以下属性:
      ImageFieldFile.name
      ImageFieldFile.path
      ImageFieldFile.url

      所有这些属性都返回 unicode 字符串。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-04-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-04-15
        相关资源
        最近更新 更多