如何使用 perform_create 中的 Validator 来限制 Django Rest Framework 的图片上传大小?
How can I use Validator in perform_create to limit image upload size for Django Rest Framework?
在我看来,我可以将图像的分辨率限制在特定的宽度和高度范围内,但我不知道如何使用这种方法来限制图像的上传大小。有解决办法吗?
我的看法:
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()
假设 serializer.validated_data['image']
是 django.db.models.ImageField
的实例,您可以检查 .size
.
来源:https://github.com/django/django/blob/main/django/db/models/fields/files.py#L69
在我看来,我可以将图像的分辨率限制在特定的宽度和高度范围内,但我不知道如何使用这种方法来限制图像的上传大小。有解决办法吗?
我的看法:
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()
假设 serializer.validated_data['image']
是 django.db.models.ImageField
的实例,您可以检查 .size
.
来源:https://github.com/django/django/blob/main/django/db/models/fields/files.py#L69