python画图保存到指定_python – 将Matplotlib绘图图像保存到Django模型中

在Python webapp中使用matplotlib创建图表,并尝试将其图像保存到Django的Plot模型中。当创建图表并保存时,图表图像以<_io.StringIO对象>形式保存在主目录,但在模型中保存的图像却是空白。代码示例展示了如何从POST请求获取数据,绘制图表,然后将其保存到ImageField。
摘要由CSDN通过智能技术生成

出于学习目的,我正在创建一个使用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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值