Django:让管理员获取图像文件,但将其存储为base64字符串

时间:2017-06-11 22:35:23

标签: python django image django-models base64

我的任务是创建一个管理视图,以便用户可以输入一个图像文件,然而它将作为模型字段存储为base64字符串,而不是存在于我们服务器上的静态文件目录中。

我不清楚这个过程究竟是如何完成的,我是否应该从管理视图中拦截POST请求并预处理它以存储在字段中?我应该覆盖基本表单的保存方法吗?由于我是Django的新手并且无法产生工作效果,我对不同的方法感到有些困惑。

这是我的设置:

models.py

from django.db import models

class Product(models.Model):
    organization = models.ForeignKey(Organization)
    name = models.CharField(max_length=50) 
    logo = models.TextField() 

admin.py

from django.contrib import admin
from .models import Product 

class ProductAdmin(admin.ModelAdmin):
    exclude = ('logo',)

admin.site.register(Product, ProductAdmin)

misc.py

#how i'd process an image?
from PIL import Image
from base64 import b64encode

def image_to_b64(image_file):
    imgdata = Image(image_file)
    encoded = b64encode(open(imgdata, 'rb'))
    return encoded

1 个答案:

答案 0 :(得分:3)

from django.db import models

class Product(models.Model):
    organization = models.ForeignKey(Organization)
    name = models.CharField(max_length=50) 
    logo = models.TextField()
    logo_image = models.ImageFiled(null=True, blank=True, upload_to='logo')


def image_to_b64(image_file):
    import base64
    with open(image_file.path, "rb") as f:
        encoded_string = base64.b64encode(f.read())
        return encoded_string

from django.dispatch import receiver
from django.db.models.signals import post_save, m2m_changed


@receiver(post_save, sender=Product)
def create_base64_str(sender, instance=None, created=False, **kwargs):
    if created:
        instance.logo = image_to_b64(instance.logo_image)
        instance.logo_image.delete()
        instance.save()