I have a folder with image files. Unfortunately, some files contain a space in their name. Django is able to load these images if I run the app on the development server (via python manage.py runserver
) but not if I run it in production. The reason is that Django converts " "
to "%20"
.
For example, if my folder contains the following files:
... then this code will have the following result:
# 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
I could of course rename all image filenames that contain space characters by replacing the spaces with underscores. But that's a bit awkward as a chemical analysis system is constantly feeding new image files to the folder and the system's software will occasionally introduce spaces in the filenames. I do not have control over this.
So is there a way to force Django to load images even if they contain space characters?
It's not Good Practice But, you can do using custom 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())