1, first add a folder in your project, such as: system
Add and file under the folder __init__.py
storage.py
, and storage.py
add the following code:
#-*-coding:utf-8-*- fromDjango.core.files.storageImportFilesystemstorage fromDjango.httpImportHttpResponseclassimagestorage (filesystemstorage): fromDjango.confImportSettingsdef __init__(Self, location=settings. Media_root, Base_url=settings. Media_url):#InitializeSuper (Imagestorage, self).__init__(location, Base_url)#overriding the _save method def_save (self, Name, content):
#name为上传文件名称ImportOS, time, Random#file name extensionext = os.path.splitext (name) [1] #file directoryD =os.path.dirname (name)#define the file name, month and day, and minute random numberfn = Time.strftime ('%y%m%d%h%m%s') FN= fn +'_%d'% Random.randint (0,100) #rewrite the composition file nameName = Os.path.join (d, Fn +ext)#calling the parent class method returnSuper (Imagestorage, self). _save (name, content)
2. models.py
Add the following code to the file:
from Import imagestoragepic=models. ImageField (upload_to='img/%y/%m/%d', Storage=imagestorage ()) # If you upload a file, you can change the ImageField to Filefield
3, this solves the problem, the effect is as follows:
How Django renames uploaded images (renaming uploaded files)