我的模特:
class MyFile(models.Model):
file = models.FileField(upload_to="myfiles", max_length=500)
slug = models.SlugField(max_length=500, blank=True)
当文件名包含特殊字符时,例如' '(空格),特殊字符将自动替换为下划线。 在哪里(在哪个函数中)会发生这种情况?如何禁用此自动验证?
由于
更新
对以下代码有何评论?谢谢
"""
https://docs.djangoproject.com/en/1.9/_modules/django/core/files/storage/#Storage.get_valid_name
Overwrite get_valid_name() function,
"""
class OverwriteStorage(FileSystemStorage):
def get_valid_name(self, name):
print "name=", name
return name
class MyFile(models.Model):
file = models.FileField(upload_to="myfiles", max_length=500, storage=OverwriteStorage())
答案 0 :(得分:1)
这取决于您的存储空间。 FileField
在存储空间ref上调用storage.get_valid_name
。
您可能会覆盖该功能(取决于您的存储空间),但我认为保留原样可能更好。您始终可以使用名称字段。
如果您使用FileSystemStorage
,则会调用django.utils.text.py
,后者会使用下划线(ref)替换空格。
修改强>
假设你使用默认的FileSystemStorage
,这里是如何覆盖它:
创建一个文件(可能在你的主应用程序中)
storage.py:
from django.core.files.storage import FileSystemStorage
from django.utils.deconstruct import deconstructible
@deconstructible
class CustomFileSystemStorage(FileSystemStorage):
def get_valid_name(self, name):
return name
(您可能需要@deconstructible
装饰器进行迁移)
现在您有两种选择来使用此存储。您可以在模型中明确指定它:
我的模特:
class MyFile(models.Model):
file = models.FileField(upload_to="myfiles", max_length=500, storage=CustomFileSystemStorage)
slug = models.SlugField(max_length=500, blank=True)
或者您可以在settings.py
:
DEFAULT_FILE_STORAGE = '{yourapp}.storage.CustomFileSystemStorage'
(ref)
答案 1 :(得分:0)
实施在django source code中。我不确定如何禁用它,为什么不保持原样呢?