出于学习目的,我正在创建一个使用matplotlib制作绘图的webapp,我想将该绘图的图像保存到Plot模型的图形字段中,但是当我创建一个绘图时,它会将空白图像保存到/媒体/数字/目录.我这样做的方式与其他帖子的建议方式相同但不起作用.
更多信息
当我创建绘图时,绘图图像将保存在我的django项目的主目录中,其名称类似于< _io.StringIO对象,位于0xb1ac69ec>,但正如我所说,保存在模型中的绘图图像是空白的.如果重要的话,我也使用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)
在Python webapp中使用matplotlib创建图表,并尝试将其图像保存到Django的Plot模型中。当创建图表并保存时,图表图像以<_io.StringIO对象>形式保存在主目录,但在模型中保存的图像却是空白。代码示例展示了如何从POST请求获取数据,绘制图表,然后将其保存到ImageField。
1058

被折叠的 条评论
为什么被折叠?



