前言
django通过自带的ImageField可以实现图片上传,如果想在列表页面也显示图片缩略图的话,可以用django-stdimage插件来实现
django-stdimage
django-stdimage的github文档地址https://github.com/codingjoe/django-stdimage
实现以下功能的Django Field:
- Django-Storages兼容(S3)
- 将图像调整为不同大小
- 访问模型级别的缩略图,不需要模板标签
- 保留原始图像
- 异步渲染(Celery&Co)
- 多线程和处理以获得最佳性能
- 限制接受的图像尺寸
- 将文件重命名为标准化名称(使用可调用的upload_to)
环境准备,直接通过pip安装,最新版本Version: 4.0.1
pip install django-stdimage
并加入'stdimage'到INSTALLED_APP在你的settings.py
在settings.py配置上传文件的目录地址,参考前面一篇https://www.cnblogs.com/yoyoketang/p/10653878.html
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
官方案例
变量在字典中指定。键将是引用已调整大小的图像的属性。变量可以定义为元组或字典。
from django.db import models
from stdimage.models import StdImageField
class MyModel(models.Model):
# works just like django's ImageField
image = StdImageField(upload_to='path/to/img')
# creates a thumbnail resized to maximum size to fit a 100x75 area
image = StdImageField(upload_to='path/to/img',
variations={'thumbnail': {'width': 100, 'height': 75}})
# is the same as dictionary-style call
image = StdImageField(upload_to='path/to/img', variations={'thumbnail': (100, 75)})
# creates a thumbnail resized to 100x100 croping if necessary
image = StdImageField(upload_to='path/to/img', variations={
'thumbnail': {"width": 100, "height": 100, "crop": True}
})
## Full ammo here. Please note all the definitions below are equal
image = StdImageField(upload_to='path/to/img', blank=True, variations={
'large': (600, 400),
'thumbnail': (100, 100, True),
'medium': (300, 200),
})
用于在模板中使用生成的变量myimagefield.variation_name。如
<a href="{{ object.myimage.url }}"><img alt="" src="{{ object.myimage.thumbnail.url }}"/></a>
实践案例
通过上面的案例介绍,接下来写个实际的案例练习下
# models.py
from django.db import models
from django.utils import timezone
from datetime import datetime
from stdimage.models import StdImageField
# Create your models here.
class UploadImage(models.Model):
'''上传图片功能'''
name = models.CharField(max_length=30, verbose_name="名称", default="") # 标题
image = StdImageField(max_length=100,
upload_to='path/to',
verbose_name=u"传图片",
variations={'thumbnail': {'width': 100, 'height': 75}})
# 时间可编辑
add_time = models.DateTimeField(default=datetime.now, verbose_name=u"添加时间")
def url(self):
if self.image:
return self.image.url
else:
return "url为空"
def image_img(self):
if self.image:
href = self.image.url # 点击后显示的放大图片
src = self.image.thumbnail.url # 页面显示的缩略图
# 插入html代码
image_html = '<a href="%s" target="_blank" title="传图片"><img alt="" src="%s"/>'%(href, src)
return image_html
else:
return '上传图片'
image_img.short_description = '图片'
image_img.allow_tags = True # 列表页显示图片
class Meta:
verbose_name = "传图片"
verbose_name_plural = verbose_name
def __str__(self):
return self.name
adminx.py注册表信息
# adminx.py
import xadmin
from xadmin import views
from .models import UploadImage
class ControlImage(object):
# 显示不要用image,而应该用image_img
list_display = ['name', 'image_img', 'url', 'add_time']
xadmin.site.register(UploadImage, ControlImage)
urls.py配置图片的URL地址访问,要不然查询详情的时候缩略图无法正常显示
from . import settings
from django.views.static import serve
urlpatterns = [
url(r'^media/(?P<path>.*)$', serve, {"document_root": settings.MEDIA_ROOT}),
]
配置好之后,执行 makemigrations 和migrate,同步数据
python manage.py makemigrations
python manage.py migrate
xadmin后台显示
列表显示缩略图,点击可以放大
关于allow_tags的用法可以看下一篇https://www.cnblogs.com/yoyoketang/p/10659137.html