How Django renames uploaded images (renaming uploaded files)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.