I am trying to update a div element in my html page using a png image that is returned from a Django server.
In my client side script, where I send ajax POST request when a button is clicked, I have
$('#mybtn').click(function (event) { event.preventDefault(); $.ajax({ url: "/analysis", type: "POST", data: { 'data': $("#analysis_list").val(), csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value }, success: function (response) { $('#imagediv').html('<img src=' + response + ' />'); }, }); });
In my views.py I have -
def analysis(request): dataFromClient = dict(request.POST)['data'][0] pathToImg = testAnalytics(dataFromClient) img = Image.open(pathToImg) response = HttpResponse(content_type="image/png") img.save(response, "PNG") return response
Where the testAnalytics method generates an image that will be displayed in accordance with the data sent by the client, and returns the path to it. Image imported from PIL .
I ran into a problem of rendering the image on the client side javascript. When I assign the response to src attribute of the <img> , I see the raw image data in the browser instead of the image (as discussed here - How to update a div with an image in Django? ). I am not sure where I am going wrong.
I also tried base64 encoding in the answer as follows (but not sure if I implemented correctly) -
success: function (response) { $('#imagediv').html('<img alt="Embedded Image" src="data:image/png;base64,' + response + '" />'); }
I mentioned the following links to go to this question -
Django: how to make an image using a template
Serve dynamically generated image with Django
I am new to web programming as well as to Django. Any information about the problem would be really helpful. Thanks in advance.