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.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/93d6e921-1a49-48c7-bb1f-e182e588b2a7%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to