我的目标是有一个简单的表单,允许用户输入一个函数来绘制图形,以及一个显示窗口,一旦用户点击提交按钮,我希望 numpy 和 matplotlib 获取表单数据并生成一个图形,然后在新网页中显示该数字。
到目前为止,我按照“创建联系表单视图”来生成表单并使数据可用。我发现这个可以让我显示图像。然而,图像就像这样占据了整个浏览器窗口。我希望该图像显示在我的网页中。我对 Django 很陌生,如果这没有意义或信息不够,我很抱歉。如果需要,我很乐意提供说明或其他信息。
这是我的应用程序的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)
这是我的 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)')
慕娘9325324
拉风的咖菲猫
相关分类