Coder Social home page Coder Social logo

django-croppable-images's Introduction

django-croppable-images

django-croppable-images is a reusable app that helps you easily add image cropping functionality to your Django projects.

When you use this app, your original images as well as their corresponding cropped versions will be saved to your default storage. The crop coordinates are also saved so that they can be displayed to and adjusted by your end-users via a seamless front-end interface implemented as a custom Django form field + widget (using Jcrop).

To use django-croppable-images, you will need to install django-imagekit which is used to manage the actual cropping of image files.

How to Use

Add a CroppableImageField to your model where you would otherwise have a stock Django ImageField.

Also add an ImageSpecField (from django-imagekit) to your model and set its image_field argument to the name of the CroppableImageField you created above. For the processors argument (the first positional argument in the ImageSpecField constructor), use the provided get_crop_processor() utility function and pass in the same image_field argument as before.

Here's an example:

from django.db import models
from imagekit.models import ImageSpecField
from croppable.fields import CroppableImageField
from croppable.utils import get_crop_processor

class MyFavoriteModel(models.Model):
    name = models.CharField(max_length=200)
    some_other_field = models.CharField(max_length=200)
    my_image = CroppableImageField(invalidate_on_save=['my_image_cropped'], upload_to='my_image_folder', blank=True)
    my_image_cropped = ImageSpecField(get_crop_processor(image_field='my_image'), image_field='my_image')

CroppableImageField is a model field that is just a subclass of Django's ImageField, so it takes all of the arguments supported by its superclass (e.g. upload_to and blank in the example above)

In most cases, you'll want to pass in the optional invalidate_on_save argument to your CroppableImageField and set it to a list containing just the name of your corresponding ImageSpecField (as is done in the above example). This tells django-image-kit that it needs to re-process the image modifications associated with each ImageSpecField in the list at some point after (or at the same time as) your model is saved. This is necessary so that the cropped image file is changed if the crop coordinates are changed.

If you're familiar with ImageKit, by "re-process" above, we are just calling invalidate() on the corresponding ImageSpecField. We recommend using ImageKit's non-default NonValidatingImageCacheBackend . In the context of django-croppable-images, all this does is make it so your cropped images are updated each time your model is saved. Simply add the following line to your settings:

IMAGEKIT_DEFAULT_IMAGE_CACHE_BACKEND = 'imagekit.imagecache.NonValidatingImageCacheBackend'

Finally, to hook up the front-end interface all you need to do is use the included CroppableImageField form field (as opposed to the model field above) to your ModelForm.

In the context of the Django Admin, you would just create your own ModelForm and have it use a CroppableImageField for the field that corresponds to your image. Then simply tell your ModelAdmin to use that form. Here's a full example:

from django import forms
from django.contrib import admin
from myapp.models import MyFavoriteModel
from croppable.forms import CroppableImageField

class MyFavoriteModelAdminForm(forms.ModelForm):
    my_image = CroppableImageField()

    class Meta:
        model = MyFavoriteModel

class MyFavoriteModelAdmin(admin.ModelAdmin):
    form = MyFavoriteModelAdminForm

admin.site.register(MyFavoriteModel, MyFavoriteModelAdmin)

Now on the Admin site for MyFavoriteModel you'll have an awesome Jcrop-powered widget that lets you define a crop region for your image. When you press save, your original image will be uploaded and a new image file will be saved that contains the cropped version.

To display the cropped image in a template, just use the attribute on your model that contains the ImageSpecField:

<img src="{% my_favorite_model_instance.my_image_cropped.url %}">

How it Works

The CroppableImageField model field subclasses the Django ImageField and uses its own CroppableImageFieldFile (a subclass of ImageFieldFile which overrides the file-saving functionality). Instead of saving just the filename to the database, CroppableImageFieldFile saves both the filename as well as the crop coordinates (in CSV format), separated by a configurable delimiter. To change the default, just set CROPPABLE_IMAGE_FIELD_DELIMITER to whatever you want it to be in your settings (note that this must contain only valid characters for use in UNIX filenames).

The CroppableImageField form field subclasses the Django MultiValueField form field and uses both an ImageField and CharField (for the crop coordinates). This form field appends the crop coordinates to the image's filename (along with the delimiter) and passes it off to the model field / field file which knows how to parse it.

django-croppable-images's People

Contributors

danxshap avatar djw avatar rclmenezes avatar theskumar avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

django-croppable-images's Issues

How do you instantiate CroppableImageField in a form?

Also, quick question - I have a form like this:
class UserEditForm(forms.Form): first_name = forms.CharField(max_length=200, label="First Name") last_name = forms.CharField(max_length=200, label="Last Name") picture = CroppableImageField(required=False, label="Picture")

And I'm trying to instantiate it with this:
form = UserEditForm({'first_name': person.user.first_name, 'last_name': person.user.last_name, 'picture': (person.picture, person.picture_cropped) })

Do you happen to know what I'm doing wrong? Thanks!

Dumpdata only serializes filename

When using Django 1.5.5, I'm running into the issue where dumpdata is only outputting the filename of the CroppableImageField, without its coord_csv.

It seems that the best way to solve this is to use value_to_string():
https://docs.djangoproject.com/en/1.6/howto/custom-model-fields/#django.db.models.Field.value_to_string

Adding this to CroppableImageField seems to work for me:

def value_to_string(self, obj):
        if obj.picture:
            value = obj.picture.filename + IMAGE_FIELD_DELIMITER + obj.picture.coords_csv
        else:
            value = ''
        return self.get_prep_value(value)

Note that this doesn't solve loaddata...

Edit:
Found a way to make loaddata work! Overload get_db_prep_save():
https://docs.djangoproject.com/en/1.5/howto/custom-model-fields/#django.db.models.Field.get_db_prep_save

def get_db_prep_save(self, value, connection):
        return value.filename + IMAGE_FIELD_DELIMITER + value.coords_csv

jQuery 1.7 compatibility, bootstrap compatibility and admin page bug

Hi Dan-

I like your project.

However, I've been trying to use django-croppable-images for a project of mine and I've had a couple issues:

  • Without jQuery in the form media, cropped_image_admin.js breaks in the admin page. To fix this, I added a short:
    if (typeof($) == 'undefined') { jQuery = django.jQuery; $ = django.jQuery; }
  • I used Bootstrap and it's default CSS broke Jcrop's images. You can fix it if you add this to the jquery.Jcrop.css:
    .jcrop-holder img { max-width: none; vertical-align: none; }
  • Lastly, it's compliant with jQuery 1.4.2, but not with a newer version. I'm coming up with a few edits that will make it compatible with jQuery 1.7 (for example, jQuery 1.7 references HTML FileLists though the prop function and not the attr function).

I'm going to do what I can to make all these changes and pull request.

Cheers!

Broken with imagekit 3.0

I believe that imagekit made changes to how the cache is processed. When using the latest version, I get a can't pickle error when saving. Could it be the invalidate method on save?

Using CroppableImageField in ModelForms

Hey, we're trying to use django-croppable-images for our forms, but the readme is a little ambiguous on how to properly do this. Could you make an example in the readme or provide an example here?

This is what I'm doing currently:

models.py

from croppable.models import CroppableImageField
from croppable.utils import get_crop_processor

class Project(models.Model):

   image = CroppableImageField(
        invalidate_on_save=['project_page', 'preview_pitch'],
        upload_to="img/projectimage",
        blank=True)
    project_page = ImageSpec(
        get_crop_processor(image_field='image'),
        image_field='image')
    preview_pitch = ImageSpec(
        get_crop_processor(image_field='image'),
        image_field='image')

    ...

forms.py

from projects.models import Project
from croppable.forms import CroppableImageField

class MyModelForm(forms.ModelForm):

    class Meta:
        model = Project
        fields = ['image', 'title', 'content']

    image = CroppableImageField(blank=True)
    title = ...

When loading this form, all I get is the standard imagefield widget and it fails to save, with no issues or warnings, even with DEBUG = True.

If you can point me in the direction of this issue (I see there is another similar issue already opened) I'll be happy to fix and submit it.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.