Python 在字段本身旁边的管理页面中显示多对多字段图像
首先,在你读了这个问题之后,请随意建议编辑标题,因为我不确定键入什么 我有这种等级制度。。Python 在字段本身旁边的管理页面中显示多对多字段图像,python,django,Python,Django,首先,在你读了这个问题之后,请随意建议编辑标题,因为我不确定键入什么 我有这种等级制度。。 石头->子类型->子类型->子类型,只要石头在现实生活中有一个子类型。所以不知道我会在一块特定的石头上添加多少次子类型。让我们检查一下 # models.py from django.db import models from django.utils.safestring import mark_safe class Stone(models.Model): name = ... s
石头
->子类型
->子类型
->子类型
,只要石头在现实生活中有一个子类型。所以不知道我会在一块特定的石头上添加多少次子类型。让我们检查一下
# models.py
from django.db import models
from django.utils.safestring import mark_safe
class Stone(models.Model):
name = ...
sub_type = models.ForeignKey('StoneSubType', on_delete=models.DO_NOTHING ,related_name='stones', blank=True, null=True)
class StoneSubType(models.Model):
name = ...
sub_type = models.ManyToManyField('self', related_name='sub_types', blank=True)
class StoneSubtypeImage(models.Model):
stone = models.ForeignKey('StoneSubType', on_delete=models.CASCADE, related_name='images')
image = models.ImageField(default=None, upload_to='stone_subtypes/')
class StoneImage(models.Model):
stone = models.ForeignKey('Stone', on_delete=models.CASCADE, related_name='images')
image = models.ImageField(default=None, upload_to='stones/')
def image_tag(self):
return mark_safe(f'<img src="{self.image.url}">')
它将子类型下的图像显示为一个单独的字段。解决方案越来越接近。所以您希望图像显示在子类型选择列表旁边,在那里可以选择多个子类型?你能添加一个模型图像来展示你想要的输出吗?我会这样做并编辑这个问题。我编辑了,子类型的图像,而不仅仅是在我选择子类型后应该显示的一个图像,也就是说,将它移到右边。我问过之后一直在尝试,我找到了一些东西,我让它们显示出来(不在正确的位置tho)现在我将更新代码
class StoneSubtypeAdmin(admin.ModelAdmin):
inlines = [StoneSubtypeImagesInline]
search_fields = ['name', 'category', 'price', 'color__name',]
filter_horizontal = ['sub_type']
fields = ['name', 'sub_type', 'sub_type_images', 'category', 'block_num', 'salab_num', 'barcode', 'commercial_size', 'price', 'details', 'town', 'country', 'color', 'surface' ]
readonly_fields = ['sub_type_images']
def sub_type_images(self, obj):
if obj.sub_type is not None:
output = '' # html here
for sub_type in obj.sub_type.all():
for image in sub_type.images.all():
output += (
f'<div class="column">'
f'<h3 class="heading"> {obj.name} </h3>'
f'<a href="/admin/core/stonesubtype/{sub_type.pk}/"><img src="{image.image.url}" style="max-height: 300px"></a>'
f'</div>'
)
output = f'<div class="image_grid"> {output}</div> <style> .image_grid {{display: grid; grid-template-columns: repeat(auto-fill, 250px); grid-template-rows: auto auto auto; .heading {{ font-size: 20p !important; display: inline-block; }} .column {{ display: flex; flex-direction: column }} </style>'
return mark_safe(output)