Skip to content

Instantly share code, notes, and snippets.

@mitchtabian
Created October 15, 2019 17:49
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save mitchtabian/975f55e9e51b7bc13baf9a6c97be626e to your computer and use it in GitHub Desktop.
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