Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

binascii.Error: Incorrect padding in python django

I am trying to save the base64 encoded image in the django rest framework. First of all, we make a code to insert the base64 encoded image into the imagefield and test it, and the following error appears.

binascii.Error: Incorrect padding

What I don't understand is that I've used the same code before and there was no such error. Can you help me? Here is my code.

serializers.py

from rest_framework import serializers
from .models import post, comment

class Base64ImageField (serializers.ImageField) :

    def to_internal_value (self, data) :
        from django.core.files.base import ContentFile
        import base64
        import six
        import uuid

        if isinstance(data, six.string_types):
            if 'data:' in data and ';base64,' in data :
                header, data = data.split(';base64,')

            try :
                decoded_file = base64.b64decode(data)
            except TypeError :
                self.fail('invalid_image')

            file_name = str(uuid.uuid4())[:12]
            file_extension = self.get_file_extension(file_name, decoded_file)
            complete_file_name = "%s.%s" % (file_name, file_extension, )
            data = ContentFile(decoded_file, name=complete_file_name)

        return super(Base64ImageField, self).to_internal_value(data)

    def get_file_extension (self, file_name, decoded_file) :
        import imghdr

        extension = imghdr.what(file_name, decoded_file)
        extension = "jpg" if extension == "jpeg" else extension

        return extension

class commentSerializer (serializers.ModelSerializer) :

    class Meta :
        model = comment
        fields = '__all__'

class postSerializer (serializers.ModelSerializer) :
    author = serializers.CharField(source='author.username', read_only=True)
    image1 = Base64ImageField(use_url=True)
    image2 = Base64ImageField(use_url=True)
    image3 = Base64ImageField(use_url=True)
    image4 = Base64ImageField(use_url=True)
    image5 = Base64ImageField(use_url=True)
    comment = commentSerializer(many=True, read_only=True)

    class Meta:
        model = post
        fields = ['pk', 'author', 'title', 'text', 'image1', 'image2', 'image3', 'image4', 'image5', 'tag1', 'tag2', 'tag3', 'tag4', 'tag5', 'comment']
like image 698
leedjango Avatar asked Jul 10 '26 00:07

leedjango


1 Answers

I'm not sure this applies to your situation, depending on where you're storing your encoded data.

I had the same error, but it related to some encoded session data. I cleared out the session data (cookies, cache etc) in the browser Devtools, and it fixed my issue.

Just posting this in case it applies or helps others who come along for the same reason.

like image 90
Peter Peterson Avatar answered Jul 11 '26 14:07

Peter Peterson