Django Admin图片上传与缩略图处理

  • 我是根据我自己的项目的models字段做的,仅供参考

  • myApp项目下的models.py文件中添加代码:

from PIL import Image
import os
from ttsx.settings import MEDIA_ROOT
# 上传图片重命名要用到的lib
import os, datetime, uuid

# 创建原始图片名称
def generate_filename(instance, filename):
    """
    安全考虑,生成随机文件名
    """
    directory_name = datetime.datetime.now().strftime('upload_img/%Y/%m')
    filename = uuid.uuid4().hex + os.path.splitext(filename)[-1]
    return os.path.join(directory_name, filename)

# 创建缩略图名称
def generate_filename_thumb(instance, filename):
    directory_name = datetime.datetime.now().strftime('upload_img/thumb/%Y/%m')
    filename = uuid.uuid4().hex + os.path.splitext(filename)[-1]
    return os.path.join(directory_name, filename)

# 制作缩略图
from django.db.models.fields.files import ImageFieldFile
UPLOAD_ROOT = generate_filename
THUMB_ROOT = "upload_img/thumb" # 这个是最终的缩略图要保存的路径
def make_thumb(path, size = 180):
    pixbuf = Image.open(path)
    width, height = pixbuf.size

    if width > size:
        delta = width / size
        height = int(height / delta)
        pixbuf.thumbnail((size, height), Image.ANTIALIAS)
        return pixbuf

#商品表
class Goods(models.Model):
    #商品名称
    goods_name = models.CharField(max_length=30, null=True)
    #商品简介
    goods_desc = models.CharField(max_length=150, null=True)
    #商品价格
    goods_price = models.DecimalField(max_digits=8, decimal_places=2, null=True)
    #商品单价
    goods_height = models.CharField(max_length=10, default='500g')
    #商品描述
    goods_info = models.TextField(null=True)
    #商品图片
    goods_img = models.ImageField(upload_to=generate_filename, null=True)
    #商品缩略图
    goods_thumb = models.ImageField(upload_to=generate_filename_thumb, null=True)
    #商品添加时间
    add_time = models.DateTimeField(auto_now_add=True, null=True)
    #商品更新时间
    update_time = models.DateTimeField(auto_now=True, null=True)
    #关联的外键model名称
    foreign_link = models.ForeignKey(Category)

    # 保存上传图片的缩略图
    def save(self):
        super(Goods, self).save()  # 将上传的图片先保存一下,否则报错
        base, ext = os.path.splitext(os.path.basename(self.goods_img.path))
        thumb_pixbuf = make_thumb(os.path.join(MEDIA_ROOT, self.goods_img.name))
        relate_thumb_path = os.path.join(THUMB_ROOT, base + '_thumb' + ext)
        thumb_path = os.path.join(MEDIA_ROOT, relate_thumb_path)
        thumb_pixbuf.save(thumb_path)
        self.goods_thumb = ImageFieldFile(self, self.goods_thumb, relate_thumb_path)
        super(Goods, self).save() # 再保存一下,包括缩略图等
  • myApp项目目录下的admin.py文件中添加代码:
# 设置缩略图
    readonly_fields = ('goods_thumb',)  # 因为不需要在后台修改该项,所以设置为只读
    def get_readonly_fields(self, request, obj=None):
        if obj:  # editing an existing object
            return self.readonly_fields
        return self.readonly_fields

admin.site.register(Goods, GoodsInfoAdmin)

你可能感兴趣的:(Django Admin图片上传与缩略图处理)