This article introduces the problem of uploading file names in customized FileField through example code. Interested friends can refer to it
The upload_to attribute in FileField can set the storage directory and name of the uploaded file. It It can be a string or a callable, such as a method.
When the value of upload_to is set to a method, the name of the uploaded file can be modified. 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, so the value of upload_to can also be Is a class that defines the __call__ method.
For example, 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 @deconstructible class 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 the Model can be defined as follows:
class MyModel(models.Model): upload = models.FileField(upload_to=TimeStampFileName('media/'), )
The above is the detailed content of Detailed explanation of FileField custom upload file name. For more information, please follow other related articles on the PHP Chinese website!