I am trying to display images in django html web page from mongodb. I saved images in mongodb using gridfs with vendor_id as an extra value. Then i retrieved them like :
my models.py:
def getImages(self, vendor_id):
img_name = []
img_ids = []
images = []
for each in self.files.find({'vendor_id':vendor_id}): ####self.files is a variable which store value db['fs.files']
img_ids.append(each['_id'])
img_name.append(each['name'])
for iid in img_ids:
images.append(self.gfs.get(iid).read())
return images
my views.py:
def vendorData(request):
vendors = Vendors()
if request.method == 'GET':
vendor_id = request.GET.get('vendor_id')
if vendors.checkValidVendorId(vendor_id) == False:
return HttpResponse('Invalid Vendor Id.')
else:
vendor_details = vendors.getVendorDetails(vendor_id)
vendor_name = vendor_details[0]
restaurant_name = vendor_details[1]
images = vendors.getImages(vendor_id)
context_dict = {'vendor_id':vendor_id,
'vendor_name':vendor_name,
'restaurant_name':restaurant_name
'images':images}
return render(request, 'vendor_data.html', context_dict)
I passed the binary data of multiple images to views.py in a list. How to show this data in django web page?
Note: I can show these images by saving them temporarily. But is there any other way i can display these images without saving?
You could probably use the "data" uri format, which allows you to pass the image as a base64-encoded string. Of course, you'll need to encode the images first in your getImages
function:
for iid in img_ids:
images.append(base64.b64encode(self.gfs.get(iid).read()))
and in the template you can output the data directly:
{% for image in images %}
<img src="data:image/png;base64,{{ img }}">
{% endfor %}
(obviously, replace png with jpg or whatever as necessary).
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.