Django 如何将相关对象添加到管理索引视图?
我希望能够从列表显示视图中显示图像是否与每个产品关联。 我似乎遇到了麻烦,因为我正在处理一个关联的对象 models.py 管理员 出于某种原因,大写字母_case_name()在列表视图中显示良好。 _product()的照片一直显示(无) 我还尝试在photo_for_产品方法中使用pdb,但Django不喜欢这样 我还尝试将callable放在ModelAdmin方法之前,但是,这造成了很多错误:Django 如何将相关对象添加到管理索引视图?,django,django-admin,Django,Django Admin,我希望能够从列表显示视图中显示图像是否与每个产品关联。 我似乎遇到了麻烦,因为我正在处理一个关联的对象 models.py 管理员 出于某种原因,大写字母_case_name()在列表视图中显示良好。 _product()的照片一直显示(无) 我还尝试在photo_for_产品方法中使用pdb,但Django不喜欢这样 我还尝试将callable放在ModelAdmin方法之前,但是,这造成了很多错误: ProductAdmin.list_display[1], 'photo_for_produ
ProductAdmin.list_display[1], 'photo_for_product' is not a callable or an attribute of 'ProductAdmin' or found in the model 'Product'.
编写一个以字符串形式返回必要信息的方法,并将该方法的名称添加到管理类上的列表显示中。编写一个以字符串形式返回必要信息的方法,并将该方法的名称添加到管理类上的列表显示中。您的问题并不清楚您到底想要什么输出为。您说您想知道“是否已关联图像”-如果是,您可以尝试以下方法:
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
产品(自身、obj)的def照片:
images=self.imagemain\u set.all()
如果图像:
返回“”%images[0]。photo.url
其他:
返回“”
photo_for_product.allow_tags=True
您的问题并不清楚您希望输出的确切内容。您说您想知道“是否已关联图像”-如果是,您可以尝试以下方法:
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
产品(自身、obj)的def照片:
images=self.imagemain\u set.all()
如果图像:
返回“”%images[0]。photo.url
其他:
返回“”
photo_for_product.allow_tags=True
我希望输出是图像路径的字符串。显然,问题在于图像[0]。photo是am ImageFieldFile而不是字符串 默认情况下,ImageFieldFile似乎具有以下属性:
ImageFieldFile.name
ImageFieldFile.path
ImageFieldFile.url
所有这些属性都返回unicode字符串。我希望输出是图像路径的字符串。显然,问题在于图像[0]。photo是am ImageFieldFile而不是字符串 默认情况下,ImageFieldFile似乎具有以下属性:
ImageFieldFile.name
ImageFieldFile.path
ImageFieldFile.url
所有这些属性都返回unicode字符串。我希望输出是图像路径的字符串。显然,问题在于图像[0]。照片是am ImageFieldFile而不是字符串。我希望输出是图像路径的字符串。显然,问题在于图像[0]。photo是am ImageFieldFile而不是字符串。