0

I am trying to interactively display plots from matplotlib in django. From this answer, I see that I can send the plot from a view with this code:

response = HttpResponse(mimetype="image/png")
# create your image as usual, e.g. pylab.plot(...)
pylab.savefig(response, format="png")
return response

So the view sends the plot as an Httpresponse, but how do I reference that in the html code of the template? I'm guessing it will be something like this but am having a tough time finding examples of html code:

<img src={ some reference to the plot here }>

Again, I think I can generate the plot with a view but am not sure how to reference that output in the html template.

5
  • You've missed the point. The src needs to point to the URL that serves the view. Commented Mar 14, 2018 at 15:47
  • So... In that view, if I set template_name = "app/plot.html" then the src for the plot will be that path? I'll try that. Thanks for help. Commented Mar 14, 2018 at 15:54
  • No, that's not what I said at all. See my answer for more explanation. Commented Mar 14, 2018 at 15:54
  • 1
    Oh... the URL that I have set in urls.py in urlpatterns with path() Commented Mar 14, 2018 at 15:57
  • I get it now. Thanks again! Commented Mar 14, 2018 at 15:58

1 Answer 1

1

A view is served by a URL. This view exists purely to serve the content of an image, therefore you should simply use its URL as the src in your img tag. For instance:

urlpatterns = [
    path('path/to/my/image', views.my_image, 'my_image')
]

...

def my_image(request, ...):
    response = HttpResponse(mimetype="image/png")
    # create your image as usual, e.g. pylab.plot(...)
    pylab.savefig(response, format="png")
    return response

...

<img src="{% url "my_image" %}">
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.