Ole*_*nko 31 django django-models
我已经定义了一个包含图像链接的模型.有没有办法在模型项目列表中显示图像?我的模型看起来像这样:
class Article(models.Model):
url = models.CharField(max_length = 200, unique = True)
title = models.CharField(max_length = 500)
img = models.CharField(max_length = 100) # Contains path to image
def __unicode__(self):
return u"%s" %title
Run Code Online (Sandbox Code Playgroud)
有没有办法将图像与标题一起显示?
Mic*_*ael 60
您可以使用其他名称创建模型实例方法,为其输出允许HTML标记,并将此方法添加为列表字段.这是一个例子:
首先添加一个新方法,返回包含图像的HTML:
class Article(models.Model):
...
def admin_image(self):
return '<img src="%s"/>' % self.img
admin_image.allow_tags = True
Run Code Online (Sandbox Code Playgroud)
然后将此方法添加到列表中:
class ArticleAdmin(admin.ModelAdmin):
...
list_display = ('url', 'title', 'admin_image')
Run Code Online (Sandbox Code Playgroud)
小智 13
def image_tag(self, obj):
return u'<img src="%s" />' % obj.image
image_tag.short_description = 'Image'
image_tag.allow_tags = True
Run Code Online (Sandbox Code Playgroud)
并在您的admin.py中添加:
readonly_fields = ('image_tag',)
Run Code Online (Sandbox Code Playgroud)
更新django 2.0.6
我在最新的django 2.0.6中解决了这个问题.我想在django-admin的listview中获取图像thubnail和更多细节.
下面的图片是我的默认管理列表视图.
这是我的 models.py:
from django.db import models
from django.utils.safestring import mark_safe
# Create your models here.
class Product(models.Model):
title = models.CharField(max_length=120)
description = models.TextField()
price = models.DecimalField(decimal_places = 2, max_digits = 20, default = 00.00)
image = models.ImageField(upload_to=change_image_name, null=True, blank=True)
def image_tag(self):
if self.image:
return mark_safe('<img src="%s" style="width: 45px; height:45px;" />' % self.image.url)
else:
return 'No Image Found'
image_tag.short_description = 'Image'
def __str__(self):
return self.title
Run Code Online (Sandbox Code Playgroud)
请注意我必须在图像字符串上使用mark_safe(),否则你将在django-admin中获取转义的html代码而不是thubnail
最后这是我的 admin.py
from django.contrib import admin
from .models import Product
# Register your models here.
class ProductAdmin(admin.ModelAdmin):
list_display = ('title', 'description', 'price', 'image_tag')
admin.site.register(Product, ProductAdmin)
Run Code Online (Sandbox Code Playgroud)
在这里我们也要注册ProductAdmin类,我不知道它并没有用.
您也可以直接在管理员中添加图像
class ArticleAdmin(admin.ModelAdmin):
def admin_image(self, obj):
return '<img src="%s"/>' % obj.img
admin_image.allow_tags = True
list_display = ('url', 'title', 'admin_image')
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
20558 次 |
最近记录: |