Noodles for Django

Half-baked noodles of ideas for little bits of Django functionality

This project is maintained by Brant

Assets from Images

The "assets from images" portion of Noodles is designed as a series of Mixins for models that will automatically detect ImageField fields on your model and create "assets" from those images.

By "assets", I mean resized, optimized, and optionally cropped versions of the original ImageField image.

Easy, Out-of-the-Box Mixins (for Convenience)

There is a base mixin that allows for further customization, but there are two implementations of that base mixin which allow the mixins to be much more quickly attached to your models.

HalfQuarterAssetsMixin

Probably the fastest way to start generating multiple assets from your ImageField fields is to just add the "HalfQuarterAssetsMixin" to your model definition.

class MyModel(HalfQuarterAssetsMixin, models.Model):
    image = models.ImageField(upload_to="path/to/uploads")

That will automatically generate 2 assets per image field in the model - one at half of the original size and one at a quarter of the original size.. Those assets are then accessible using a simple attribute syntax added to instances of that model:

instance = MyModel.objects.get(pk=1)
instance.image_half.url
instance.image_quarter.url

Or, in templates:

{{ instance.image_half.url }}
{{ instance.image_quarter.url }}

DefinedWidthsAssetsFromImagesMixin

If you want to specify the width of your assets while maintaining the aspect ratio, you can use the DefinedWidthsAssetsFromImagesMixin.

You just add the mixin to your model, along with adding a method: get_dimensions().

class MyModel(DefinedWidthsAssetsFromImagesMixin, models.Model):
    image = models.ImageField(upload_to="path/to/uploads")

    def get_dimensions(self):
        """ returns a list of desired widths """
        return [400, 600, 1000]

The above configuration will create 3 assets automatically when instances of the model are saved; one with a width of 400px, one at 600px, and one at 1000px.

Those generated assets are then accessable using dynamically added attribues of the model:

instance = MyModel.objects.get(pk=1)
instance.image_400.url
instance.image_600.url
instance.image_1000.url

Or, in templates:

{{ instance.image_400.url }}
{{ instance.image_600.url }}
{{ instance.image_1000.url }}

With the DefinedWidthsAssetsFromImagesMixin you can also optionally add another method to your model: get_quality() which returns the quality (0-100) that JPEG assets will be saved at. Defaults to 75.

class MyModel(DefinedWidthsAssetsFromImagesMixin, models.Model):
    image = models.ImageField(upload_to="path/to/uploads")

    def get_dimensions(self):
        """ returns a list of desired widths """
        return [400, 600, 1000]

    def get_quality(self):
        """ returns quality argument for jpegs 
        defaults to 75 """
        return 100