I was tasked with creating an admin view such that a user could input an image file, which however would be stored as a base64 string as a model field rather than exist in a static files dir on our server.
I'm unclear on how exactly this process would be done, should I be intercepting the POST request from the admin view and pre-processing it to be stored in the field? Should I be overwriting the save method of the base form? I'm a little confused by the different methods as I'm new to Django and have been unable to produce a working result.
Here's my setup:
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
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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.