提问人:Snoeren01 提问时间:11/16/2023 更新时间:11/16/2023 访问量:46
我可以强制 Django 加载文件名中带有空格的图像吗?
Can I force Django to load images with space in the filename?
问:
我有一个包含图像文件的文件夹。不幸的是,某些文件的名称中包含空格。如果我在开发服务器上运行应用程序(通过),Django 能够加载这些图像,但如果我在生产环境中运行它,则无法加载这些图像。原因是 Django 转换为 .python manage.py runserver
" "
"%20"
例如,如果我的文件夹包含以下文件:
- 图片1.png
- image2 测试.png
- image3%20test.png (只是为了了解发生了什么)
...那么这段代码将产生以下结果:
# In settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = ('D:/Data/Images')
# In the HTML template
<img src="/media/image1.png"/> # image loads on the development and production server
<img src="/media/image2 test.png"/> # image loads only on the development server
<img src="/media/image3 test.png"/> # image loads only on the production server
当然,我可以通过用下划线替换空格来重命名所有包含空格字符的图像文件名。但这有点尴尬,因为化学分析系统不断向文件夹提供新的图像文件,并且系统的软件偶尔会在文件名中引入空格。我无法控制这一点。
那么有没有办法强制 Django 加载图像,即使它们包含空格字符呢?
答:
2赞
Mahammadhusain kadiwala
11/16/2023
#1
这不是好的做法,但是,您可以使用自定义 FileSystemStorage
来做
custom_storage.py
from django.core.files.storage import FileSystemStorage
class CustomStorage(FileSystemStorage):
def get_valid_name(self, name):
return name # No modification to the name
models.py
from django.db import models
from .custom_storage import CustomStorage # Import the CustomStorage class
class YourModel(models.Model):
image = models.ImageField(upload_to='images/', storage=CustomStorage())
评论
0赞
Snoeren01
11/17/2023
感谢您指出创建 CustomStorage 类的选项。作为一个 Django 新手,我不知道这是可能的。但是,在仔细研究之后,我决定遵循 Van Onsem willeM_的建议,避免使用空格的文件名。我用一个脚本解决了它,该脚本重命名了上游系统创建的文件。就我而言,这是更简单的解决方案。但是 CustomStorage 对于我未来的应用程序来说似乎是一个很棒的功能。
上一个:RGB图像到灰度图像
评论