I want to set null true when saving image in django rest api with base64

697 Views Asked by At

My models are:

class Profile(models.Model):

store_picture1 = models.ImageField(null=True, blank=True)
store_picture2 = models.ImageField(null=True, blank=True)
store_picture3 = models.ImageField(null=True, blank=True)
store_picture4 = models.ImageField(null=True, blank=True)
store_picture5 = models.ImageField(null=True, blank=True)
store_picture6 = models.ImageField(null=True, blank=True)

def save(self,*args, **kwargs):

    if self.user_picture:
        im = Image.open(self.user_picture)
        output = BytesIO()
        im = im.resize((740, 610))
        im.save(output, format='JPEG', quality=120)
        im.save(output, format='PNG', quality=120)
        output.seek(0)
        self.user_picture = InMemoryUploadedFile(output, 'ImageField', "%s.jpg" % 
        self.user_picture.name.split('.')[0], 'image/jpeg',sys.getsizeof(output), None)
        self.user_picture = InMemoryUploadedFile(output, 'ImageField', "%s.png" % 
        self.user_picture.name.split('.')[0], 'image/png',sys.getsizeof(output), None)


        self.user_picture = InMemoryUploadedFile(output, 'ImageField', "%s.jpg" % 
        self.user_picture.name.split('.')[0], 'image/jpeg',sys.getsizeof(output), None)
        self.user_picture = InMemoryUploadedFile(output, 'ImageField', "%s.png" % 
        self.user_picture.name.split('.')[0], 'image/png',sys.getsizeof(output), None)

and this is my serializers.py class:

class Base64ImageField(serializers.ImageField):

def to_internal_value(self, data):

    # Check if this is a base64 string
    if isinstance(data, six.string_types):
        # Check if the base64 string is in the "data:" format
        if 'data:' in data and ';base64,' in data:
            # Break out the header from the base64 content
            header, data = data.split(';base64,')

        # Try to decode the file. Return validation error if it fails.
        try:
            decoded_file = base64.b64decode(data)
        except TypeError:
            self.fail('invalid_image')

        # Generate file name:
        file_name = str(uuid.uuid4())[:12] # 12 characters are more than enough.
        # Get the file name extension:
        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):

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

    return extension


class ProfileUpateSerializer(ModelSerializer):


user_picture = Base64ImageField(
    max_length=None, use_url=True,
)

store_picture1 = Base64ImageField(
    max_length=None, use_url=True,
)

store_picture2 = Base64ImageField(
    max_length=None, use_url=True,
)

store_picture3 = Base64ImageField(
    max_length=None, use_url=True,
)

store_picture4 = Base64ImageField(
    max_length=None, use_url=True,
)

store_picture5 = Base64ImageField(
    max_length=None, use_url=True,
)

store_picture6 = Base64ImageField(
    max_length=None, use_url=True,
)

class Meta:
    model = Profile

    fields ='__all__'

i did set null=true and blan=true in my models.py for imageField but when I want sent with image base64 with api notifies that it needs this field how cat in set null and blank true in my serializer class

In fact I think I should add something to class ProfileUpateSerializer in serializers.py

1

There are 1 best solutions below

0
On

You can pass required=False in Base64ImageField. ie

user_picture = Base64ImageField(
    max_length=None, use_url=True, required=False
)