binascii.Error: Incorrect padding in python django

Viewed 6990

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']
5 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.

I had the same error. I do all things clear cache but it doesn't work. Now change the browser to Mozilla. Now it's working.

I had the same issue. I guess it was caused by me using django 4.0.1 in the beginning and later switching back to django 2.2... (Maybe your issue was not caused by this but I just want to provide some idea on where the problem might be to all the reader who has this issue and visit this page.)

Django 4.0.1 should directly save the session data in string into the database but Django 2.2 saves and reads base64 encoded data into / from the same column session_data in table django_session in DB.

The string failed in base64.b64decode() in my case is .eJxVjEEOwiAQRe_C2pABCgWX7j0DmRlAqoYmpV0Z765NutDtf-_9l4i4rTVuPS9xSuIslDj9boT8yG0H6Y7tNkue27pMJHdFHrTL65zy83K4fwcVe_3WGtkEHfLg2IMroL1VZA0BFGMJPJhRkdEucypY2CfA7C2HgRHGor14fwDNWjfC:1nERxl:5jJRHXpQH7aZrf2-C99MnTIWARd_cUag76Xa2YjW1yw, which is obviously not valid base64 string since symbols : - . . do not exist in base64 character list at all.

enter image description here

My full traceback info is:

Internal Server Error: /admin
Traceback (most recent call last):
  File "C:\Users\Public\django2.2\lib\site-packages\django\contrib\sessions\backends\base.py", line 189, in _get_session
    return self._session_cache
AttributeError: 'SessionStore' object has no attribute '_session_cache'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "C:\Users\Public\django2.2\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "C:\Users\Public\django2.2\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\Public\django2.2\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Public\django2.2\lib\site-packages\django\contrib\admin\sites.py", line 241, in wrapper
    return self.admin_view(view, cacheable)(*args, **kwargs)
  File "C:\Users\Public\django2.2\lib\site-packages\django\utils\decorators.py", line 142, in _wrapped_view
    response = view_func(request, *args, **kwargs)
  File "C:\Users\Public\django2.2\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func
    response = view_func(request, *args, **kwargs)
  File "C:\Users\Public\django2.2\lib\site-packages\django\contrib\admin\sites.py", line 212, in inner
    if not self.has_permission(request):
  File "C:\Users\Public\django2.2\lib\site-packages\django\contrib\admin\sites.py", line 186, in has_permission
    return request.user.is_active and request.user.is_staff
  File "C:\Users\Public\django2.2\lib\site-packages\django\utils\functional.py", line 256, in inner
    self._setup()
  File "C:\Users\Public\django2.2\lib\site-packages\django\utils\functional.py", line 392, in _setup
    self._wrapped = self._setupfunc()
  File "C:\Users\Public\django2.2\lib\site-packages\django\contrib\auth\middleware.py", line 24, in <lambda>
    request.user = SimpleLazyObject(lambda: get_user(request))
  File "C:\Users\Public\django2.2\lib\site-packages\django\contrib\auth\middleware.py", line 12, in get_user
    request._cached_user = auth.get_user(request)
  File "C:\Users\Public\django2.2\lib\site-packages\django\contrib\auth\__init__.py", line 182, in get_user
    user_id = _get_user_session_key(request)
  File "C:\Users\Public\django2.2\lib\site-packages\django\contrib\auth\__init__.py", line 59, in _get_user_session_key
    return get_user_model()._meta.pk.to_python(request.session[SESSION_KEY])
  File "C:\Users\Public\django2.2\lib\site-packages\django\contrib\sessions\backends\base.py", line 54, in __getitem__
    return self._session[key]
  File "C:\Users\Public\django2.2\lib\site-packages\django\contrib\sessions\backends\base.py", line 194, in _get_session
    self._session_cache = self.load()
  File "C:\Users\Public\django2.2\lib\site-packages\django\contrib\sessions\backends\db.py", line 44, in load
    return self.decode(s.session_data) if s else {}
  File "C:\Users\Public\django2.2\lib\site-packages\django\contrib\sessions\backends\base.py", line 100, in decode
    encoded_data = base64.b64decode(session_data.encode('ascii'))

It's possible you run the server in a different Environment, Activate that environment and try to run the server again.

incase the env folder is in your current Path here's what to do

kill the server and then run

source env/bin/activate
python manage.py runserver
Related