'Need to override save method for image field and save it as base64 string using django

models.py

class Organisation(models.Model):

    org_id = models.CharField(max_length=50,default=uuid.uuid4, editable=False, unique=True, primary_key=True)
    org_name = models.CharField(unique=True,max_length=100)
    org_code = models.CharField(unique=True,max_length=20)
    org_mail_id = models.EmailField(max_length=100)
    org_phone_number = models.CharField(max_length=20)
    org_address = models.JSONField(max_length=500, null=True)
    product = models.ManyToManyField(Product, related_name='products')
    org_logo = models.ImageField(upload_to=upload_org_logo, null=True, blank=True,)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

I need to save an image which I get in image field on org_logo as a base64 string and upload it to the s3 bucket which I have given as file storage using django storages. Note: File object will be the input I will be getting from the frontend(React). I need to override the save method to save it as base64 string.

I have referred many data but I couldn't able to get it properly. Can anyone please guide me to what exactly needs to be changed and where so that I could understand better.



Solution 1:[1]

import base64
image = open(form.cleaned_data['image'], 'rb')
image_read = image.read()
image_64_encode = base64.encodebytes(image_read)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Rajeel Rajput