Created
October 15, 2019 17:49
Star
You must be signed in to star a gist
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class BlogPostUpdateSerializer(serializers.ModelSerializer): | |
class Meta: | |
model = BlogPost | |
fields = ['title', 'body', 'image'] | |
def validate(self, blog_post): | |
try: | |
title = blog_post['title'] | |
if len(title) < MIN_TITLE_LENGTH: | |
raise serializers.ValidationError({"response": "Enter a title longer than " + str(MIN_TITLE_LENGTH) + " characters."}) | |
body = blog_post['body'] | |
if len(body) < MIN_BODY_LENGTH: | |
raise serializers.ValidationError({"response": "Enter a body longer than " + str(MIN_BODY_LENGTH) + " characters."}) | |
image = blog_post['image'] | |
url = os.path.join(settings.TEMP , str(image)) | |
storage = FileSystemStorage(location=url) | |
with storage.open('', 'wb+') as destination: | |
for chunk in image.chunks(): | |
destination.write(chunk) | |
destination.close() | |
# Check image size | |
if not is_image_size_valid(url, IMAGE_SIZE_MAX_BYTES): | |
os.remove(url) | |
raise serializers.ValidationError({"response": "That image is too large. Images must be less than 2 MB. Try a different image."}) | |
# Check image aspect ratio | |
if not is_image_aspect_ratio_valid(url): | |
os.remove(url) | |
raise serializers.ValidationError({"response": "Image height must not exceed image width. Try a different image."}) | |
os.remove(url) | |
except KeyError: | |
pass | |
return blog_post |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment