5

I have a form that sends an image via Django Rest Framework. The serializer is as shown:

class AvatarSerializer(serializers.ModelSerializer):
    avatar = Base64ImageField(validators=[image_validation])

    class Meta:
        model = Profile
        fields = ('avatar',)

I also have image validation that checks the size of the image so that it is not over 12MB:

def image_validation(image):
    # 12MB
    MAX_FILE_SIZE = 12000000
    print(image.name)
    if image.size > MAX_FILE_SIZE:
        print(image.size)
        raise ValidationError("File size too big!")

The image size gets printed out when I try to upload an image greater than 12mb, however, I get this response in Chrome's network tab: Failed to load response data I read that it might be because of the image's size (I was trying to upload a 30mb image). The ValidationError is not shown and the user gets a 500 server error. How can I fix this?

5
  • There is server timeout per request. If the request taking too much time it will kill and return 500 Internal Error before going into serializer.
    – Mirza715
    Commented Jan 30, 2020 at 7:17
  • @user2896120 are you using django-extra-fields for Base64ImageField?
    – funnydman
    Commented Jan 30, 2020 at 9:21
  • @Mirza715 How do I make it so that if it takes too much time it returns a valid error? Commented Jan 30, 2020 at 20:05
  • @funnydman I am using Base64ImageField Commented Jan 30, 2020 at 20:09
  • @user2896120 see this stackoverflow.com/questions/42155616/… . On the side note try to compress the files before uploading it to server
    – Mirza715
    Commented Jan 31, 2020 at 5:41

1 Answer 1

6

serializers has feature field-level-validation that validate the property before returns.

https://www.django-rest-framework.org/api-guide/serializers/#field-level-validation

class AvatarSerializer(serializers.ModelSerializer):
    avatar = Base64ImageField()

    def validate_avatar(self, image):
        # 12MB
        MAX_FILE_SIZE = 12000000
        print(image.name)
        if image.size > MAX_FILE_SIZE:
            print(image.size)
            raise ValidationError("File size too big!")


    class Meta:
        model = Profile
        fields = ('avatar',)
3
  • Can i know, after usage of this, what error you are getting.
    – Saisiva A
    Commented Feb 3, 2020 at 1:50
  • 2
    You need to return image in the validate_avatar func, unless you're going to get empty value for avatar field, Commented Oct 28, 2020 at 7:39
  • It seems validate_avatar should add a return image.
    – Sam Chiu
    Commented Apr 6, 2022 at 12:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.