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.