Home > Web Front-end > JS Tutorial > body text

Detailed explanation of FileField custom upload file name

巴扎黑
Release: 2017-08-23 13:56:33
Original
1775 people have browsed it

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 &#39;user_{0}/{1}&#39;.format(instance.user.id, filename)
class MyModel(models.Model):
 upload = models.FileField(upload_to=user_directory_path)
Copy after login

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)
Copy after login

The FileField in the Model can be defined as follows:


class MyModel(models.Model):
 upload = models.FileField(upload_to=TimeStampFileName(&#39;media/&#39;), )
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!