我有一个包含图像文件的文件夹。不幸的是,某些文件的名称中包含空格。如果我在开发服务器上运行应用程序(通过
python manage.py runserver
),Django 能够加载这些图像,但如果我在生产中运行它则不能。原因是 Django 将 " "
转换为 "%20"
。
例如,如果我的文件夹包含以下文件:
...那么这段代码将得到以下结果:
# 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 加载图像,即使它们包含空格字符?
这不是好的做法但是,您可以使用自定义
FileSystemStorage
from django.core.files.storage import FileSystemStorage
class CustomStorage(FileSystemStorage):
def get_valid_name(self, name):
return name # No modification to the name
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())