How to display image file from sftp remote server in django template?
- We have 2 servers. One of them is for media files and the other one is for django project server(ngnx+gunicorne).
- Our media server is local(internal). We want to access to media server from inside the project with sftp storage package which includes paramiko. we don't want to access media server via URL (http,https).
HttpResponse(file, content_type=type)
can display the image file as a big picture but we want to pass the image file to django template for display in html file like<a href="{{ course.get_absolute_url }}"><img src="{{images}}" alt=""></a>
- We know HttpResponse is not a good solution but we use it below code for explained our problem.
# view
def coursesPageView(request):
courses = Course.objects.filter(is_published=True)
image_data =[imageRespone(data) for data in courses]
data = {
'published_courses_list':courses,
'images' : image_data
}
return render(request, 'pages/course2.html', data)
def imageRespone(valid_image):
if sfs.exists(valid_image.image.name):
file = sfs._read(valid_image.image.name)
type, encoding = mimetypes.guess_type(valid_image.image.name)
response = HttpResponse(file, content_type=type)
return response
else:
return HttpResponse('404 Not Found')
#course2.html
<a href="{{ course.get_absolute_url }}"><img src="{{images}}" alt=""></a>
What you can do is mounting a shared drive into your webserver pointing to your media server (Samba for linux). Then with Django you can specify the localisation of your statics file.
For example :
import os
MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.abspath(os.path.join(os.sep, 'srv', 'media'))
STATIC_URL = '/app/static/'
STATIC_ROOT = os.path.abspath(os.path.join(os.sep, 'srv', 'static'))
Pay attention to the permissions between the web server and the mounted folder.