Reputation: 67
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?
Upvotes: 0
Views: 1166
Reputation: 67
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
Upvotes: 1
Reputation: 1397
First of all check whether image is saving that media folder. If it saving only problem with serving the image means you need to add this line of code in Project Urls
from django.conf.urls import url, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^admin/', admin.site.urls),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
So whenever you are trying to serve the image django will automatically append the url and serve the static datas. For Further reference use this . Let me know if this works
Upvotes: 0