3π
β
Letβs say you want to generate a simple graph/image after a user enters the x
and y
co-ordinates.
Requirements:
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:
- Generate an image using
matplotlib
. - Save it as a
StringIO
object. - Encode the
StringIO
object tobase64
. - 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
- [Django]-How to pass date and id through url in django
- [Django]-How to use django migrate without confirmation
- [Django]-Wrap python decorator with another decorator
- [Django]-Do websockets send and receive full messages?
Source:stackexchange.com