Django-image-cropping Django.How

Author avatar wrote on 26/05/2022

Django-image-cropping is an app for cropping uploaded images via Django’s admin backend using Jcrop.

Installation

pip install django-image-cropping

pip install easy-thumbnails

Edit setting.py file


INSTALLED_APPS = [
    ...
    'easy_thumbnails',
    'image_cropping',
]

from easy_thumbnails.conf import Settings as thumbnail_settings
THUMBNAIL_PROCESSORS = (
    'image_cropping.thumbnail_processors.crop_corners',
) + thumbnail_settings.THUMBNAIL_PROCESSORS

Configuration

Add an ImageRatioField to the model that contains the ImageField for the images you want to crop.

It simply stores the boundaries of the cropped image. It expects

1.The name of the associated ImageField

2.The desired size of the cropped image as arguments.

The size is passed in as a string and defines the aspect ratio of the selection as well as the minimum size for the final image:


from django.db import models
from image_cropping import ImageRatioField

class MyModel(models.Model):
    image = models.ImageField(blank=True, upload_to='uploaded_images')
    # size is "width x height"
    cropping = ImageRatioField('image', '430x360')

Size warning (Optional)

size_warning=True

You can warn users about crop selections that are smaller than the size defined in the ImageRatioField. When users try to do a smaller selection, a red border appears around the image.

To use this functionality for a single image add the size_warning parameter to the ImageRatioField:


cropping = ImageRatioField('image', '430x360', size_warning=True)

You can enable this functionality project-wide by adding the following line to your settings:


IMAGE_CROPPING_SIZE_WARNING = True

Admin Integration

Add the ImageCroppingMixin to your ModelAdmin:


from django.contrib import admin
from image_cropping import ImageCroppingMixin

class MyModelAdmin(ImageCroppingMixin, admin.ModelAdmin):
    pass

admin.site.register(MyModel, MyModelAdmin)

If your setup is correct you should now see the enhanced image widget that provides a selection area.

Image App Example

1.Install “Django image cropper“ and “easy thumbnails“

pip install django-image-cropping

pip install easy-thumbnails

Create app by typing command in our terminal


python manage.py startapp image

Edit setting.py file


INSTALLED_APPS = [
    ...
    'image.apps.ImageConfig',
    'easy_thumbnails',
    'image_cropping',
]

from easy_thumbnails.conf import Settings as thumbnail_settings
THUMBNAIL_PROCESSORS = (
    'image_cropping.thumbnail_processors.crop_corners',
) + thumbnail_settings.THUMBNAIL_PROCESSORS

2.Edit image/models.py:


from django.db import models
from image_cropping import ImageRatioField, ImageCropField

class Image(models.Model):
    image_field = ImageCropField(upload_to='image/')
    cropping = ImageRatioField('image_field', '120x100', allow_fullsize=True)
    cropping_free = ImageRatioField('image_field', '300x230',
                                    free_crop=True, size_warning=True)

    def get_cropping_as_list(self):
        if self.cropping:
            return list(map(int, self.cropping.split(',')))

class ImageFK(models.Model):
    image = models.ForeignKey(Image, on_delete=models.CASCADE)
    cropping = ImageRatioField('image__image_field', '120x100') 

and run “makemigrations” and “migrate” command in terminal

3.Edit image/admin.py


from django.contrib import admin
from image_cropping.admin import ImageCroppingMixin
from .models import Image, ImageFK

class ImageFKAdmin(ImageCroppingMixin, admin.ModelAdmin):
    pass

class ImageAdmin(ImageCroppingMixin, admin.ModelAdmin):
    pass

admin.site.register(Image, ImageAdmin)
admin.site.register(ImageFK, ImageFKAdmin)

4.Create and edit image/urls.py


from django.urls import path

from . import views

urlpatterns = [
    path('', views.add, name='image_add'),
    path('/', views.add, name='image_add')
]

and edit main urls.py file


urlpatterns = [
    ...
    path('image/', include('image.urls')),
    ...
]

5.Create and edit image/forms.py


from django import forms

from .models import Image


class ImageForm(forms.ModelForm):
    class Meta:
        model = Image
        fields = ('image_field', 'cropping', 'cropping_free')

6.Edit image/views.py


from django.urls import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404, render

from image_cropping.utils import get_backend

from .forms import ImageForm
from .models import Image, ImageFK

def add(request, image_id=None):
    image = get_object_or_404(Image, pk=image_id) if image_id else None
    form = ImageForm(instance=image)
    if request.method == "POST":
        form = ImageForm(request.POST, request.FILES, instance=image)
        if form.is_valid():
            image = form.save()
            return HttpResponseRedirect(reverse('image_add', args=(str(image.pk),)))

    return render(request, 'image/add.html', {'form': form, 'image': image})

7.Create templates folder and edit file 'image/add.html'

8.inside 'base.html' add {{ form.media }} between and tags

CRUDgen Django CRUD generator