storage.py
# 给上传的图片重命名 from django.core.files.storage import FileSystemStorage from django.http import HttpResponse class ImageStorage(FileSystemStorage): from django.conf import settings def __init__(self, location=settings.MEDIA_ROOT, base_url=settings.MEDIA_URL): # 初始化 super(ImageStorage, self).__init__(location, base_url) # 重写 _save方法 def _save(self, name, content): # name为上传文件名称 import os, time, random # 文件扩展名 ext = os.path.splitext(name)[1] # 文件目录 d = os.path.dirname(name) # 定义文件名,年月日时分秒随机数 fn = time.strftime('%Y%m%d%H%M%S') fn = fn + '_%d' % random.randint(0, 100) # 重写合成文件名 name = os.path.join(d, fn + ext) # 调用父类方法 return super(ImageStorage, self)._save(name, content)
model.py
import django.utils.timezone as timezone from django.db import models from django.contrib import admin from .storage import ImageStorage # Create your models here. class Urls(models.Model): id = models.AutoField(primary_key=True) title = models.CharField(verbose_name="标题",max_length=255) created_at = models.DateTimeField(verbose_name="创建时间",default = timezone.now) url = models.ImageField(upload_to='images/%Y%m',storage=ImageStorage(),blank=True, verbose_name='图片', null=True) readonly_fields = ['image_data'] def __str__(self): return self.title class Meta: verbose_name = '图片管理' verbose_name_plural = '图片管理'