Save A Matplotlib Figure to A File Along with Displaying it on The Browser Django
<p>I am very new to Django and the following is a detailed explanation of the problem I am trying to resolve using Django Python. </p>

<p><strong>Problem:-</strong></p>

<p>Upload a multiple csv files (<strong>five files total</strong>) and then take those files and construct five figures corresponding to the uploaded files. Finally, I want to have a single page in which I ask the user to upload the files and then the user will get a <strong>conformational message for files uploaded successfully</strong>. After that, the files should be displayed only if the user hit the graphing button and should display the five figures on the same webpage. </p>

<p>My attempt thus far:-</p>

<p>A snippet of My views.py:</p>

<pre><code>def Upload(request):
  list_doc = []
  for count, x in enumerate(request.FILES.getlist('files')):
             def multifiles(f):
                    with open(dir_path + x.name + str(count) + ".csv" , 'wb+') as destination:
                            list_doc.append(x.name)
                            for chunk in f.chunks():
                                    destination.write(chunk)
             multifiles(x)

  docs = list_doc
  return render_to_response("myapp/mypage.html", {'upload_num':str(count+1)+" Files uploaded successfully!", "files_list":docs}, context_instance = RequestContext(request))


def graph(request):

 plt.figure(num)
 plt.plot(x,y, color =colorcurve, label=filename)
 ax = plt.subplot(111)
 ax.plot(x,y, color =colorcurve, linewidth=1.5)
 plt.legend(fontsize = 7.9, bbox_to_anchor=(0.61, 1), loc=6, borderaxespad=0.)
 file_saved = plt.savefig(dirpath+filename, format='png')
 figure = dirpath+filename+".png"
 return render_to_response("myapp/mypage.html", {'file_saved':figure},context_instance = RequestContext(request))
</code></pre>

<p><strong>I am not sure what to use in urls.py? help please?</strong></p>

<p>In html:</p>

<pre><code>        &lt;body&gt;
            &lt;!-- Uplading files! --&gt;
            &lt;p&gt;&lt;a href="{% url 'list' %}" align="right"&gt;Return to home&lt;/a&gt;&lt;/p&gt;
            &lt;p&gt; Please, starting uploading your files &lt;p&gt;

                    &lt;form action="{% url "UploadFile" %}" method="post" enctype="multipart/form-data"&gt;
                    {% csrf_token %}
                    &lt;input type="file" name="files" multiple/&gt;
                    &lt;input type="submit" value="Upload" /&gt;
            &lt;/form&gt;

            &lt;form action="{% url "list" %}" method="post" enctype="multipart/form-data"&gt;
                    {% csrf_token %}

                    &lt;!-- input type="file" name="files" multiple/--&gt;
                    &lt;input type="submit" value="Graphing" /&gt;
            &lt;/form&gt;
             &lt;br&gt;
             &lt;div style="overflow:hidden;"&gt;
             {% load staticfiles %}


                    &lt;img src="{% static "myapp/afile1-M1" %}" alt="My image" height="400" width="400" float=left hspace="30" border="1.8" /&gt;
</code></pre>

<p>When I runserver, it displays the graph into a new window. I want to do a couple of things. One, I want to save the figure into a file. Second, display it in the same browser window without the need to go to another window.</p>

<p>Thanks a lot in advance</p>

<p>UPDATE:
If you want to draw the graph only when "Graphing" is clicked, then name your input type, hence:</p>

<pre><code>&lt;input type="submit" value="Graphing" name="graphing"/&gt;
</code></pre>

<p>and then you can check whether it has been clicked in your view:</p>

<pre><code>if request.POST.get('graphing'):
#basically means "if user has clicked the graphing button"
</code></pre>

<p>Hope this helps,</p>

<hr>

<p>Create two views:</p>

<pre><code>def draw_pie(request):
    size = request.GET.get('size')
    return render(request, 'blog/draw_pie.html', {'size':size})

from pylab import figure, axes, pie, title
from matplotlib.backends.backend_agg import FigureCanvasAgg
def pies (rquest, size):
    f = figure(figsize=(6,6))
    ax = axes([0.1, 0.1, 0.8, 0.8])
    labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
    fracs = [15,size,45, 10]
    explode=(0, 0.05, 0, 0)
    pie(fracs, explode=explode, labels=labels, autopct='%1.1f%%', shadow=True)
    title('Raining Hogs and Dogs', bbox={'facecolor':'0.8', 'pad':5})

    canvas = FigureCanvasAgg(f)
    response = HttpResponse(content_type='image/png')
    canvas.print_png(response)
    matplotlib.pyplot.close(f)
    return response
</code></pre>

<p>The first one will contain the form, the second one will draw the graph.</p>

<p>Create two urls:</p>

<pre><code>url(r'^pies/(?P&lt;size&gt;\d+)/$', views.pies, name='pies'),
    url(r'^draw_pie/$', views.draw_pie, name='draw_pie'),
</code></pre>

<p>The first one contains a parameter, or as many parameters as you like, to set the variables of the graph. I have set the size of one of the fracs in the pie chart.</p>

<p>The second one is the url for the form.</p>

<p>Create two templates, one empty one called <code>pies.html</code>:</p>

<pre><code>empty
</code></pre>

<p>and one more template called <code>draw_pie.html</code>:</p>

<pre><code> &lt;form method="GET" action="/draw_pie/"&gt;
            &lt;h1&gt;Pie Size&lt;/h1&gt;

            &lt;label&gt;
                &lt;span&gt;Size: &lt;/span&gt;
                &lt;input type="number" step = "any" id="searchBox" class="input-medium search-query"
                name="size" placeholder="size"&gt;&lt;br&gt;
            &lt;/label&gt;


            &lt;input type="submit" class="button" value="Draw Pie" &gt;
        &lt;/form&gt;

        &lt;img src="http://yourwebsite.com/pies/{{ size }}"&gt;&lt;br&gt;
</code></pre>

<p>This will give you this result:</p>

<p><a href="http://i.stack.imgur.com/T9xB4.png" rel="nofollow"><img src="http://i.stack.imgur.com/T9xB4.png" alt="enter image description here"></a></p>

<p>If you change the size to 99 and click draw, it will reload the page and creates a new graph using the parameter you just input, then calls the graph directly using the img tag. You can see the parameter being passed in the url also:</p>

<p><a href="http://i.stack.imgur.com/lis1r.png" rel="nofollow"><img src="http://i.stack.imgur.com/lis1r.png" alt="enter image description here"></a></p>

<p>I hope this helps.</p>

python django matplotlib