How to send ImageFieldFile objects fetched from the database by django to the front-end and display them
When using django as a backend, I have an image saved in the database in ImageField format, and in the view layer I get the object via orm, how can I return it to my vue frontend.
I turned the ImageField object into a string to return a JsonResponse, but the front-end only gets the name of the image when it's read
def getContent(request):
mtitle=request.GET.get('title')
row_obj=models.content.objects.filter(title=mtitle).first()
res={
"pic":str(row_obj.img),
}
print(type(row_obj.img))
return JsonResponse(res, json_dumps_params={"ensure_ascii": False})
How do I request the image to be displayed on the front end?
The image field field will hold the image path.
You should use <img src="image path">
in the frontend
Or convert image to base64.
https://stackoverflow.com/a/3715530
You have to modify the image path yourself, this is just an example.
with open(f'{static_path}/{row_obj.img}', "rb") as image_file:
res = {
"pic": base64.b64encode(image_file.read())
}