问 题
我的models.py:
pic = models.ImageField(upload_to='img/%Y/%m')
怎样给上传的图片重命名?例如:以当前上传的时间给图片命名.谢谢~!
解决方案
结贴:
1、先在你项目中添加一个文件夹如:system 在文件夹下添加__init__.py 和storage.py文件,并在storage.py中添加如下代码:
# -*- coding: UTF-8 -*-
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):
import os, time, random
# 文件扩展名
ext = os.path.splitext(name)[1]
# 文件目录
d = os.path.dirname(name)
# 定义文件名,年月日时分秒随机数
fn