Upload_to and storage not working in Django 4.1
i have just upgrade my Django from 2.x to 4.x. I had a function that not working correctly. I have been trying so many things but still not able to figure it out. So i need some help
file = models.FileField(
upload_to=get_file_path,
storage=AbsolutePathStorage(),
max_length=500,
)
from django.core.files.storage import FileSystemStorage
class AbsolutePathStorage(FileSystemStorage):
"""Storage that allows storing files given absolute paths."""
def path(self, name: str) -> str:
"""Override path validation to allow absolute paths."""
# Return name if it's a absolute path.
if name.startswith("/"):
return name
# Return regular joined path if this is a relative path.
return super().path(name)
So before upgrading Django, the file is uploaded to the upload_to folder ( outside of MEDIA_ROOT). Everything is working fine. But after i upgraded Django to 4.1. Its not working anymore and complaining about:
The joined path (upload_to) is located outside of the base path component (MEDIA_ROOT ).
Any idea ?
Thank you.
You call super().path() in your function, which is where this error is raised.
class AbsolutePathStorage(FileSystemStorage):
...
class FileSystemStorage:
def path(self, name):
return safe_join(self.location, name) # safe_join raises the error
If your upload_to function returns an absolute path, then it looks like you can just use the name as-is and no logic is need in the name() function. The assert here is just a sanity check.
class AbsolutePathStorage(FileSystemStorage):
def path(self, name: str) -> str:
assert name.startswith("/"), f"Path was not absolute: {name}"
return name