[Django]-How to display generated image to user based on form input in Django?

3πŸ‘

βœ…

Let’s say you want to generate a simple graph/image after a user enters the x and y co-ordinates.

Requirements:

  1. jQuery
  2. jQuery Form Plugin

HTML :

<form method="POST" action="/generate-image/" id="GenImgForm">
    <input type="text" name="x-coordinate" />
    <input type="text" name="y-coordinate" />
</form>

<!-- Make an empty div where the returned image will be shown -->
<div id="ShowImage"></div>

<script type="text/javascript" src="/static/path/to/jquery.js"></script>
<script type="text/javascript" src="/static/path/to/jquery.form.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
        var options = { 
            target: '#ShowImage',
        };        
        $("#GenImgForm").ajaxForm(options);
            return false;
        });
</script>

views.py :

Now, in your views, you will have to follow this approach:

  1. Generate an image using matplotlib.
  2. Save it as a StringIO object.
  3. Encode the StringIO object to base64.
  4. Send it back to the client.

Take a look at this question.

import cStringIO # use import io in Python 3x
# import base64 Use this in Python 3x

def generate_image(request):
    if request.method == 'POST':
        x_coord = request.POST['x-coordinate']
        y_coord = request.POST['y-coordinate']

        # generate a matplotlib image, (I don't know how to do that)

        sio = cStringIO.StringIO() # use io.StringIO() in Python 3x
        pyplot.savefig(sio, format="PNG")

        encoded_img = sio.getvalue().encode('Base64') # On Python 3x, use base64.b64encode(sio.getvalue())

        return HttpResponse('<img src="data:image/png;base64,%s" />' %encoded_img)
    else:
        # Do something ...
πŸ‘€xyres

1πŸ‘

My answer is almost same as the accepted answer with few working changes.

views.py :

from matplotlib import pyplot as plt
import io
plt.plot([1, 2, 3, 4])
plt.ylabel('some numbers')
sio = io.BytesIO()
plt.savefig(sio, format="png")
encoded_img = base64.b64encode(sio.getvalue())
return HttpResponse(encoded_img)

html:

<img id="plt" src=""></img>

jQuery ajax code:

  $.ajax(
   {
     headers: {"X-CSRFToken":token},
     type: "GET",
     url: "ajax/show_hcPlot",
     success: function(response){

       $("#plt").attr('src',"data:image/png;base64, " + response);
     }
   }
  )
πŸ‘€aashu

0πŸ‘

You would need to make an AJAX request to the server to serve some url via javascript (possibly with the aid of some library like jQuery). The request would pass on the data in the form and return a link to the appropriate image.

πŸ‘€ubadub

Leave a comment