繁体   English   中英

Django - 通过 seaborn 将 AxesSubplot 保存到 django models.ImageField

[英]Django - save AxesSubplot via seaborn to django models.ImageField

我试图从seaborn模块ImageField的图形保存到的Django模型。

模型.py

class HeatmapFiles(models.Model):
    username = models.ForeignKey(
        'CustomUser',
        verbose_name='Username',
        on_delete=models.CASCADE,
        blank=False
    )
    heatmap = models.ImageField(
        verbose_name='Heatmap',
        blank=False
    )

我试图通过ImageFile保存:

示例文件.py

import io
import seaborn as sns
import matplotlib.pyplot as plt
from django.core.files.images import ImageFile

sns.set()
flights_long = sns.load_dataset("flights")
flights = flights_long.pivot("month", "year", "passengers")
f, ax = plt.subplots(figsize=(9, 6))
new = sns.heatmap(flights, annot=True, fmt="d", linewidths=.5, ax=ax)

figure = io.BytesIO()
new.get_figure().savefig(figure, format='png')
image_file = ImageFile(figure.getvalue())

image_file对象在这里返回None

<ImageFile: None>

我可以保存它,但这没有意义。 如何将“新”热图对象保存为 Django 模型?

UPD:后new.get_figure().savefig(figure, format='png') figure.getvalue()实际上具有数据“B'\\ x89PNG \\ r \\ n \\ X1A \\ n \\ X00 \\ X00 ......”内.

似乎您将figure定义为空 bytesIO 并将其放入image_file = ImageFile(...) ,因此 image_file 返回 None 。 此外, new.get_figure().savefig(...)单独保存 png 文件。

将“新”堆映射对象保存为 Django 模型。

  1. new.get_figure().savefig保存文件。

  2. models.ImageField使用该文件路径,然后一个文件将被上传到 django。

Ps:我认为你需要 () 作为 get_figure()。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM