1👍
When the html loads, the browser will do a GET
request for the image base on the url that your provide in your src
attribute.
In your current view you have placed your graphing code under the post request.
def report(request):
if request.POST: ##<<---- the request is not post therefore your image will not load
form = ArticleForm(request.POST, request.FILES)
if form.is_valid():
course = form.cleaned_data['course']
course1 = str(json.dumps(list(course)))
t = course1
course_selected = ((t.replace('"',"")).replace('[',"")).replace(']',"")
values = Article.objects.filter(body=course_selected).values_list('likes')
v1=str(values)
v2=v1.replace('(',"").replace(')',"").replace(',,',"").replace(',',"").replace('[',"").replace(']',"")
num1=map(int,v2.split(" "))
fig=Figure()
ax=fig.add_subplot(111)
x=[1,2,3]
y=num1
ax.plot(x,y)
canvas=FigureCanvas(fig)
response= HttpResponse(content_type='image/png')
canvas.print_png(response)
return response
else:
form = ArticleForm()
There are a few solutions to your problem .
One is to write a different view for it. But since you need the information from the post request, I will suggest that you
- Plot the image and save it into media directory and load the image from there.
- Save the data in the post view and write a 2nd view/or a if
request.get
to return the graph instead. - Otherwise, learn a javascript graphing library, d3 and c3 are good place to start and get django to return the values.
Let me know if you need any more help or more details.
Cheers,
Biobirdman
1👍
I would suggest something similar to what @biobirdman suggested. Perhaps the simplest way that I have found in displaying dynamically created graph content is by creating a separate view for the graph and using an image tag within your HTML view that will show the graph via the defined view URL.
You could use the report
view that you have to handle the form and then if the Article
model has an article_name
for example, you could save that name in a session which can then be accessed via a separate view that generates the graph.
The graph
view then plots and displays the graph which can be linked to a designated URL. Then within your desired HTML template you can reference that URL with an image tag like below:
<img src="{% url 'graph' %}" />
This assumes that within your URL you have name="graph"
.
This is just another possibility. Ultimately it’s dependent on your project and situation on which approach is the simplest or most elegant.