|
1 | 1 | from django.contrib.sites.shortcuts import get_current_site |
2 | | -from django.core.exceptions import BadRequest, ObjectDoesNotExist |
| 2 | +from django.core.exceptions import BadRequest, ObjectDoesNotExist, ValidationError |
3 | 3 | from django.core.files.storage import default_storage |
4 | 4 | from django.db.models import QuerySet, Subquery |
5 | 5 | from django.forms.renderers import DjangoTemplates |
6 | 6 | from django.http import JsonResponse, HttpResponseBadRequest, HttpResponseNotFound |
7 | 7 | from django.utils.decorators import method_decorator |
8 | 8 | from django.utils.html import strip_spaces_between_tags |
9 | 9 | from django.utils.safestring import mark_safe |
| 10 | +from django.utils.translation import gettext_lazy as _ |
10 | 11 | from django.views import View |
11 | 12 | from django.views.decorators.http import require_GET, require_http_methods, require_POST |
12 | 13 |
|
@@ -40,6 +41,8 @@ def dispatch(self, request, *args, **kwargs): |
40 | 41 | return HttpResponseBadRequest(f"Action {self.action} not allowed.") |
41 | 42 | try: |
42 | 43 | return JsonResponse(action(request, *args, **kwargs)) |
| 44 | + except ValidationError as e: |
| 45 | + return JsonResponse({'error': e.messages}, status=422) |
43 | 46 | except Exception as e: |
44 | 47 | return HttpResponseBadRequest(str(e)) |
45 | 48 |
|
@@ -262,7 +265,15 @@ def change(self, request, file_id): |
262 | 265 | @method_decorator(require_POST) |
263 | 266 | def crop(self, request, image_id): |
264 | 267 | image = FileModel.objects.get_inode(id=image_id, mime_types=['image/*'], is_folder=False) |
265 | | - width, height = int(request.POST.get('width')), int(request.POST.get('height')) |
| 268 | + width, height = request.POST.get('width'), request.POST.get('height') |
| 269 | + width = int(width) if str(width).isdigit() else None |
| 270 | + height = int(height) if str(height).isdigit() else None |
| 271 | + if width is None and height is None: |
| 272 | + raise ValidationError(_("At least one of width or height must be given.")) |
| 273 | + if width is None: |
| 274 | + width = round(height * image.width / image.height) |
| 275 | + if height is None: |
| 276 | + height = round(width / image.width * image.height) |
266 | 277 | cropped_image_path = image.get_cropped_path(width, height) |
267 | 278 | if not default_storage.exists(cropped_image_path): |
268 | 279 | image.crop(cropped_image_path, width, height) |
|
0 commit comments