出于学习目的,我正在制作一个使用Matplotlib制作图表的Web应用程序,并且希望将该绘图的图像保存到Plot模型的figure
字段中。但是当我制作这个绘图时,它只会将空白图像保存到/media/figures/
目录中。我按照其他帖子建议的方法做了这件事,但它并没有起作用。
更多信息
当我制作这张图时,图像以<_io.StringIO object at 0xb1ac69ec>
这样的名称保存在我的Django项目的主目录中,但正如我所说,保存在模型中的图像是空白的。此外,我正在使用Python 2.7。
def simple_plot(request):
if request.method == "POST":
name = request.POST.get("name")
xvalues = request.POST.get("xvalues")
yvalues = request.POST.get("yvalues")
plots.simple_plot(request, name, xvalues, yvalues)
messages.success(request, "Plot created!")
redirect("plots:create")
return render(request, 'plots/simple.html')
用于绘制图形并创建图示实例的文件。
def simple_plot(request ,name, xvalues, yvalues):
file_name = name+".png"
xvalues = [int(x.replace(" ","")) for x in xvalues.split(",")]
yvalues = [int(y.replace(" ","")) for y in yvalues.split(",")]
figure = io.StringIO()
plot = plt.plot(xvalues, yvalues)
plt.savefig(u'%s' % figure, format="png")
content_file = ContentFile(figure.getvalue())
plot_instance = Plot(name=name, user=request.user)
plot_instance.figure.save(file_name, content_file)
plot_instance.save()
return True
绘制模型
class Plot(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
name = models.CharField(max_length=200)
figure = models.ImageField(upload_to='figures/')
timestamp = models.DateTimeField(auto_now_add=True)