我要展示我在管理order_item的图像预览(小尺寸图像)。
我基本上在这里关注这些其他问题/答案:
Django Admin Show Image from Imagefield
但是,我无法获得预期的结果。我得到这个代替:
我虽然是也许是网址,但该文件的相对路径是相同的(除了静态部分):
static/media/images/python.png
怎么了?
models.py :
class OrderItem(models.Model):
order = models.ForeignKey(Order, on_delete=models.CASCADE)
product = models.CharField(max_length= 200)
quantity = models.CharField(max_length= 200)
size = models.CharField(max_length=200)
price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name= 'PEN Price')
image = models.ImageField(upload_to='images', blank=True, null=True)
comment = models.CharField(max_length=200, blank=True, null=True, default='')
uploaded_at = models.DateTimeField(auto_now_add=True)
class Meta:
db_table = "OrderItem"
def image_thumbnail(self):
return u'<img src="%s" />' % (self.image.url)
image_thumbnail.short_description = 'Image Thumbnail'
image_thumbnail.allow_tags = True
def sub_total(self):
return self.quantity * self.price
admin.py
# Register your models here.
class OrderItemAdmin(admin.TabularInline):
model = OrderItem
fieldsets = [
# ('Customer', {'fields': ['first_name', 'last_name'], }),
('Product', {'fields': ['product'],}),
('Quantity', {'fields': ['quantity'],}),
('Price', {'fields': ['price'], }),
('Image', {'fields': ['image'], }),
('Image_Thumbnail', {'fields': ['image_thumbnail'], }),
]
readonly_fields = ['product', 'quantity', 'price', 'image', 'image_thumbnail']
can_delete = False
max_num = 0
template = 'admin/order/tabular.html'
### Order Display ###
@admin.register(Order)
class OrderAdmin(admin.ModelAdmin):
model = Order
list_display = ['id', 'first_name', 'last_name', 'email', 'total', 'reason', 'created']
list_editable = ['reason',]
list_display_links = ('id', 'email')
search_fields = ['token', 'shipping_department', 'email']
readonly_fields = ['id','created']
fieldsets = [
('ORDER INFORMATION', {'fields': ['id','token', 'total', 'created']}),
# ('BILLING INFORMATION', {'fields': ['billingName', 'billingAddress1', 'billingCity', 'billingPostCode',
# 'billingCountry', 'emailAddress']}),
('SHIPPING INFORMATION', {'fields': ['first_name', 'last_name', 'shipping_address', 'shipping_department', 'shipping_province',
'shipping_district', 'shipping_address1', 'shipping_address2']}),
]
inlines = [
OrderItemAdmin,
]
def has_delete_permission(self, request, obj=None):
return False
def has_add_permission(self, request):
return False
答案 0 :(得分:3)
从Django 1.9开始,allow_tags
已过时,您可以使用mark_safe
:
在较早的版本中,可以向该方法添加allow_tags属性,以防止自动转义。不建议使用此属性,因为它更安全地使用format_html(),format_html_join()或mark_safe()。
所以,尝试这样:
from django.utils.html import mark_safe
...
def image_thumbnail(self):
return mark_safe('<img src="%s" />' % (self.image.url))