Create a file name instance in FileField.

Source: Internet
Author: User

Create a file name instance in FileField.

The upload_to attribute in FileField can be used to set the storage directory and name of the uploaded file. It can be a string or callable, for example, a method.

When the value of upload_to is set to a method, you can modify the name of the uploaded file. The method requires two parameters: instance and filename. instance is the Model instance to which the FileField belongs, and filename is the name of the uploaded file.

Example:

 def user_directory_path(instance, filename): # file will be uploaded to MEDIA_ROOT/user_<id>/<filename> return 'user_{0}/{1}'.format(instance.user.id, filename) class MyModel(models.Model): upload = models.FileField(upload_to=user_directory_path) 

When a class defines the _ call _ method, it can also be called like func, the upload_to value can also be a class that defines the _ call _ method.

For example, you need to add a timestamp to the file name based on the upload time:

import hashlib import os import time  from django.utils.deconstruct import deconstructible   @deconstructibleclass TimeStampFileName(object):   def __init__(self, path):     self.path = os.path.join(path, "%s%s")    def __call__(self, instance, filename):     extension = os.path.splitext(filename)[1]     data = "%s_%d"%(filename,int(time.time()))     file_hash = hashlib.sha1(data).hexdigest()     return self.path % (file_hash, extension)

The FileField in Model can be defined as follows:

class MyModel(models.Model):   upload = models.FileField(upload_to=TimeStampFileName('media/'), ) 

The example of the uploaded file name in the above custom FileField is all the content shared by the editor. I hope to give you a reference and support for the help house.

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.