In my Django project I have application in which I want to load files NOT in MEDIA_ROOT. I used storage
attribute to change the place but it raise error.
I used next code but it raise error when I try to load the file. How can I fix this problem?
settings.py:
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media_root')
models.py:
from django.core.files.storage import FileSystemStorage
from os import environ
PRODUCT_STORAGE = FileSystemStorage(location=environ.get('PRODUCT_STORAGE_PATH'))
def product_file_upload_path(instance, filename):
if instance.category=="1":
path = '/category_1/' + '/%s' % filename
return path
elif instance.category=="2":
path = '/category_2/' + '%s' % filename
return path
else:
path = '%s' % filename
return path
class Product(models.Model):
file = models.FileField(
max_length=255,
blank=True,
null=True,
validators=[validate_file_extension],
storage=PRODUCT_STORAGE,
upload_to=product_file_upload_path,
)
ERROR:
The joined path (/category_1/test.pdf) is located outside of the base path component (/other_folder)
Removing the leading slash and use 'category_1/'
and 'category_2/'
.
You'll also want to remove slash from '/%s'
, otherwise you you'll end up with //
in the path. You can use os.path.join()
to prevent mistakes like this.
import os
path = os.path.join('category1', filename)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.