PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, July 31, 2022

[FIXED] How can I use Validator in perform_create to limit image upload size for Django Rest Framework?

 July 31, 2022     api, django, django-rest-framework, file-upload, image     No comments   

Issue

In my view, I'm able to restrict an image's resolution to a specific range of width and height, but I don't know how to use this very method to also restrict an image's upload size. Is there a solution to this?

My view:

class WatchListAV(generics.ListCreateAPIView):
  permission_classes = [AdminOrReadOnly]
  parser_classes = [MultiPartParser, FormParser] # Support both image and text upload.
  queryset = WatchList.objects.all()
  serializer_class = WatchListSerializer
  pagination_class = WatchListLimitOffsetPagination
  filter_backends = [filters.SearchFilter, filters.OrderingFilter]
  search_fields = ['title', 'platform__name']
  ordering_fields = ['avg_rating']
  def perform_create(self, serializer):
    if not serializer.validated_data['image']:
      raise ValidationError('No image uploaded.')
    else:
      w, h = get_image_dimensions(serializer.validated_data['image'])
      if w > 8000:
        raise ValidationError(f"Image's width is too long.")
      if w < 500:
        raise ValidationError(f"Image's width is too short")
      if h > 8000:
        raise ValidationError(f"Image's height is too tall.")
      if h < 500:
        raise ValidationError(f"Image's height is too short.")
    serializer.save()

Solution

Assuming serializer.validated_data['image'] is an instance of django.db.models.ImageField, you could check .size.

Source: https://github.com/django/django/blob/main/django/db/models/fields/files.py#L69



Answered By - Murilo Sitonio
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing