How to crop an image selected with django-filer in django admin

1.3k views Asked by At

I use django-filer to manage images. How can I crop and image after selecting one for a FilerImageField?

1

There are 1 answers

1
Petri Lehtinen On

Here's a snippet that combines django-filer and django-image-cropping. Just use CroppableFilerImageField instead of FilerImageField your models.

Note that you still have to press "Save and continue editing" after selecting the image to be able to crop.

from django.conf import settings

from filer import settings as filer_settings
from filer.fields.image import (
    AdminImageWidget, AdminImageFormField, FilerImageField,
)
from filer.models import File


class CroppableImageWidget(AdminImageWidget):
    def render(self, name, value, attrs=None):
        if value:
            file_obj = File.objects.get(pk=value)
            attrs = attrs or {}
            attrs.update({
                'class': 'crop-thumb',
                'data-thumbnail-url':
                    file_obj.thumbnails['admin_sidebar_preview'],
                'data-field-name': name,
                'data-org-width': file_obj.width,
                'data-org-height': file_obj.height,
            })

        return super().render(name, value, attrs)

    class Media:
        js = (
            filer_settings.FILER_STATICMEDIA_PREFIX + 'js/popup_handling.js',
            getattr(settings, 'JQUERY_URL',
                    'https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js'),
            "image_cropping/js/jquery.Jcrop.min.js",
            "image_cropping/image_cropping.js",
        )
        css = {'all': ("image_cropping/css/jquery.Jcrop.min.css",)}


class CroppableFormField(AdminImageFormField):
    widget = CroppableImageWidget


class CroppableFilerImageField(FilerImageField):
    default_form_class = CroppableFormField