在django-admin中水平显示InlineModel中的一个字段

时间:2018-12-17 07:52:53

标签: python django django-models django-forms django-admin

我有Inlinemodel的field('image_tag'),我想在Orderdetail模型的一行中显示。

class SampleImagesInline(admin.StackedInline):
    fields = ['image_tag']
    readonly_fields = ['image_tag']
    model = SampleImages
    extra = 0
@admin.register(OrderDetail)
class OrderDetailAdmin(admin.ModelAdmin):
    inlines = [SampleImagesInline]

默认情况下,这些是垂直显示的。如何在一行中显示?

1 个答案:

答案 0 :(得分:1)

您可以使用TabularInline。尝试这样:

class SampleImagesInline(admin.TabularInline):
    fields = ['image_tag']
    readonly_fields = ['image_tag']
    model = SampleImages
    extra = 0

更新

我想我误解了你的问题。恕我直言,您不应使用InLineAdmin。相反,请尝试这样:

from django.utils.safestring import mark_safe
...

class OrderDetailAdmin(admin.ModelAdmin):
     ...
     readonly_fields = ['image_tags',]

     def image_tags(self, obj):
         img_html = ""
         for image in obj.image_set.all():  # <-- get related images
            img_html += "<img src={}> ".format(image.image.url)

         same_line_html = '<div class="tabular inline-related last-related">{}</div>'.format(img_html)
         return mark_safe(same_line_html)

    image_tags.description = "Images"

有关获取相关对象的更多信息,请参见docs中的