Custom imagefield to accept base64 string

45 views
Skip to first unread message

Ruud Schroen

unread,
Jun 4, 2016, 8:28:34 AM6/4/16
to Django users
Hi,

I'm working on a custom field which should accept a base64 string received from the HTML canvas element, and then convert it to a image and save it to the database.

This is what I have so far:
class Base64ToImageField(models.ImageField):
    description
= "Accepts a base64 string and converts it to an image"

    def __init__(self, upload_extension="png", *args, **kwargs):
       
self.upload_extension = upload_extension
       
super(Base64ToImageField, self).__init__(*args, **kwargs)

   
def get_internal_type(self):
       
return 'ImageField'

    def to_python(self, value):
       
if isinstance(value, str):
           
try:
                image_data
= b64decode(value)
               
return ContentFile(image_data, '%s.%s' % (uuid.uuid4(), self.upload_extension))
           
except binascii.Error:
               
raise ValueError("Input value is not a valid base64 string")
       
else:
           
raise ValueError("Input type str expected, instead got %s" % type(value))

   
def formfield(self, **kwargs):
        defaults
= {'form_class': forms.CharField}
        defaults
.update(kwargs)
       
return super(Base64ToImageField, self).formfield(**defaults)

The idea is to make use of a hidden input, which gets updated by javascript everytime the user stops drawing on the canvas (mouseup event). When the user submits the form, the base64 string then gets sent to the field. If the string can be converted to a image, save it to the database.

But for testing purposes, i just want to show a text input where I can see the string.

The problem is I can't get a text input to display. Even though iI override formfield, it will always show a file input. The to_python method works, because I get a ValueError when I actually try to pass a image file.

Reply all
Reply to author
Forward
0 new messages