将Matplotlib绘图图像保存到Django模型中

eus*_*ass 8 python django plot matplotlib

出于学习目的,我正在制作一个使用matplotlib制作绘图的webapp,我想将该绘图的图像保存到figurePlot模型的字段中,但是当我创建一个绘图时,它会将空白图像保存到/media/figures/目录中.我按照其他帖子的建议做了这个,但它没有用.

更多信息 当我制作绘图时,绘图图像会保存在我的django项目的主目录中,其名称类似于<_io.StringIO object at 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')
Run Code Online (Sandbox Code Playgroud)

绘制的文件和创建的绘图实例.

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
Run Code Online (Sandbox Code Playgroud)

情节模型

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)
Run Code Online (Sandbox Code Playgroud)

Tho*_*tze 5

您的代码有几个问题:

  • 你不应该将数字保存到a StringIO而是a io.BytesIO().这是因为PNG文件的内容不是人类可读的文本而是二进制数据.

  • 另一个问题是你在传递它时如何处理BytesIO(StringIO在你的代码中)savefig.A BytesIO与文件无关(这就是拥有内存中类文件对象的全部意义),因此它没有文件名 - 这是我想要通过该u'%s' % figure表达式得到的.相反,只需写入类似文件的对象本身.

  • 第三,用一个django.core.files.images.ImageFile代替ContentFile.另外,用BytesIO对象本身初始化它,而不是它的字节值.

然后,代码的相关部分变为:

figure = io.BytesIO()
plt.plot(xvalues, yvalues)
plt.savefig(figure, format="png")
content_file = ImageFile(figure)
Run Code Online (Sandbox Code Playgroud)