I have a form containing an ImageField and a FileField
The files are uploading to the correct folders, however when I try to retrieve the url to display on screen it gives me an incorrect location
fs_img = FileSystemStorage(location='media/images/')
imageName = fs_img.save(image.name,image)
uploaded_image_url = fs_img.url(imageName)
E.G. Images upload as media/images/profile_image.jpg However when I try to retrieve the url of the file that just saved, in order to save the location to a DB, it retrieves it as media/profile_image.jpg which doesn't exist
I am aware that the default location used by FileSystemStorage is MEDIA_ROOT and that seems to be just what fs_img.url(imageName) is using where
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
Also, I have found that in the models.py file using an upload_to setting has no effect
image = models.ImageField(
upload_to = 'media/images/',
default='media/no_image.png'
)
How do I get fs_img.url(imageName) to return the correct URL so that I can save it to my database?
I think i fixed this as follows:
settings.py
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
FS_IMAGE_UPLOADS = os.path.join(MEDIA_ROOT,'images/')
FS_IMAGE_URL = os.path.join(MEDIA_URL,'images/')
FS_DOCUMENT_UPLOADS = os.path.join(MEDIA_ROOT,'documents/')
FS_DOCUMENT_URL = os.path.join(MEDIA_URL,'documents/')
views.py
image = request.FILES['image']
document = request.FILES['document']
fs_img = FileSystemStorage(
location = settings.FS_IMAGE_UPLOADS,
base_url= settings.FS_IMAGE_URL
)
imageName = fs_img.save(image.name,image)
uploaded_image_url = fs_img.url(imageName)
fs_doc = FileSystemStorage(
location = settings.FS_DOCUMENT_UPLOADS,
base_url=settings.FS_DOCUMENT_URL
)
documentName = fs_doc.save(document.name, document)
uploaded_document_url = fs_doc.url(documentName)
uploaded_image_url and uploaded_document_url values are now returning correctly