My goal is to have a simple form that allows a user to input a function to graph, along with a display window, and once the user hits the submit button, I would like numpy and matplotlib to take the form data and generate a figure, then display that figure in the new web page.
So far, I followed this where it says "Create the Contact Form View" to get the form to generate and make the data usable. I found this which allows me to display the image. However, the image takes up the whole browser window like so. I would instead like that image to display in my web page. I'm very new to Django, so sorry if this doesn't make sense or isn't enough info. I'd love to give clarification or additional info if needed.
Here is my app's views.py:
from django.shortcuts import render
from django.http import HttpResponse
from matplotlib.backends.backend_agg import FigureCanvasAgg
from .forms import GraphingInput
from .graphing_tool import graph
import io
# Create your views here.
def grapher_tool_input(request):
submitted = False
if request.method == 'POST':
form = GraphingInput(request.POST)
if form.is_valid():
cd = form.cleaned_data
fig = graph(cd['left_end'], cd['right_end'], cd['top'], cd['bottom'], cd['function'])
response = HttpResponse(content_type='image/jpg')
canvas = FigureCanvasAgg(fig)
canvas.print_jpg(response)
return response
else:
form = GraphingInput(initial={'left_end':-10, 'right_end':10, 'bottom':-10, 'top':10})
if 'submitted' in request.GET:
submitted = True
context ={
'form': form,
'submitted': submitted,
}
return render(request, 'gtdefault.html', context)
Here is my forms.py
from django import forms
class GraphingInput(forms.Form):
left_end = forms.FloatField(max_value=10000000, min_value=-10000000, label='Left End Point')
right_end = forms.FloatField(max_value=10000000, min_value=-10000000, label='Right End Point')
bottom = forms.FloatField(max_value=10000000, min_value=-10000000, label='Bottom of Window')
top = forms.FloatField(max_value=10000000, min_value=-10000000, label='Top of Window')
function = forms.CharField(min_length=1, label='f(x)')
Here is my graphing_tool.py file that generates the image:
import numpy as np
import matplotlib.pyplot as plt
import numexpr as ne
from numpy import pi, e
def graph(left, right, top, bottom, func):
step = (right - left)/10000.
x = np.arange(left, right, step)
y = ne.evaluate(func)
fig = plt.figure()
plt.xlim(left, right)
plt.ylim(bottom, top)
plt.plot(x,y)
return fig
And here is my gtdefault.html file:
{% extends 'base.html' %}
{% block content %}
{% if submitted %}
<!--Display image-->
{% else %}
<form action="" method="post" novalidate>
{{ form.as_p }}
<input type="submit" value="Graph">
{% csrf_token %}
</form>
{% endif %}
{% endblock content %}