'How can I use Validator in perform_create to limit image upload size for Django Rest Framework?
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 1:[1]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Murilo Sitonio |