django-stdimage


Namedjango-stdimage JSON
Version 6.0.2 PyPI version JSON
download
home_pagehttps://github.com/codingjoe/django-stdimage
SummaryDjango Standarized Image Field
upload_time2023-11-06 17:26:46
maintainer
docs_urlNone
authorJohannes Hoppe
requires_python
licenseMIT
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            [![version](https://img.shields.io/pypi/v/django-stdimage.svg)](https://pypi.python.org/pypi/django-stdimage/)
[![codecov](https://codecov.io/gh/codingjoe/django-stdimage/branch/master/graph/badge.svg)](https://codecov.io/gh/codingjoe/django-stdimage)
[![MIT License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)

# Django Standardized Image Field

This package has been deprecated in favor of [django-pictures][django-pictures].

## Migration Instructions

First, make sure you understand the differences between the two packages and
how to serve images in a modern web application via the [picture][picture-tag]-Element.

Next, follow the setup instructions for [django-pictures][django-pictures].

Once you are set up, change your models to use the new `PictureField` and provide the
 `aspect_ratios` you'd like to serve. Do create migrations just yet.

This step should be followed by changing your templates and frontend.
The new placeholders feature for local development should help you
to do this almost effortlessly.

Finally, run `makemigrations` and replace the `AlterField` operation with
`AlterPictureField`.

We highly recommend to use Django's `image_width` and `image_height` fields, to avoid
unnecessary IO. If you can add these fields to your model, you can use the following
snippet to populate them:

```python
import django.core.files.storage
from django.db import migrations, models
import pictures.models
from pictures.migrations import AlterPictureField

def forward(apps, schema_editor):
    for obj in apps.get_model("my-app.MyModel").objects.all().iterator():
        obj.image_width = obj.logo.width
        obj.image_height = obj.logo.height
        obj.save(update_fields=["image_height", "image_width"])

def backward(apps, schema_editor):
    apps.get_model("my-app.MyModel").objects.all().update(
        image_width=None,
        image_height=None,
    )

class Migration(migrations.Migration):
    dependencies = [
        ('my-app', '0001_initial'),
    ]

    operations = [
        migrations.AddField(
            model_name="mymodel",
            name="image_height",
            field=models.PositiveIntegerField(editable=False, null=True),
        ),
        migrations.AddField(
            model_name="mymodel",
            name="image_width",
            field=models.PositiveIntegerField(editable=False, null=True),
        ),
        migrations.RunPython(forward, backward),
        AlterPictureField(
            model_name="mymodel",
            name="image",
            field=pictures.models.PictureField(
                aspect_ratios=["3/2", "3/1"],
                breakpoints={"desktop": 1024, "mobile": 576},
                container_width=1200,
                file_types=["WEBP"],
                grid_columns=12,
                height_field="image_height",
                pixel_densities=[1, 2],
                storage=django.core.files.storage.FileSystemStorage(),
                upload_to="pictures/",
                verbose_name="image",
                width_field="image_width",
            ),
        ),
    ]
```

[django-pictures]: https://github.com/codingjoe/django-pictures
[picture-tag]: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/picture

## Why would I want this?

This is a drop-in replacement for the [Django ImageField](https://docs.djangoproject.com/en/1.8/ref/models/fields/#django.db.models.ImageField) that provides a standardized way to handle image uploads.
It is designed to be as easy to use as possible, and to provide a consistent interface for all image fields.
It allows images to be presented in various size variants (eg:thumbnails, mid, and hi-res versions)
and it provides a way to handle images that are too large with validators.


## Features

Django Standardized Image Field implements the following features:

* [Django-Storages](https://django-storages.readthedocs.io/en/latest/) compatible (eg: S3, Azure, Google Cloud Storage, etc)
* Resizes images to different sizes
* Access thumbnails on model level, no template tags required
* Preserves original images
* Can be rendered asynchronously (ie as a [Celery job](https://realpython.com/asynchronous-tasks-with-django-and-celery/))
* Restricts acceptable image dimensions
* Renames a file to a standardized name format (using a callable `upload_to` function, see below)

## Installation

Simply install the latest stable package using the following command:

```bash
pip install django-stdimage
# or
pipenv install django-stdimage
```

and add `'stdimage'` to `INSTALLED_APP`s in your settings.py, that's it!

## Usage

Now it's instally you can use either: `StdImageField` or `JPEGField`.

`StdImageField` works just like Django's own
[ImageField](https://docs.djangoproject.com/en/dev/ref/models/fields/#imagefield)
except that you can specify different size variations.

The `JPEGField` is identical to the `StdImageField` but all images are
converted to JPEGs, no matter what type the original file is.

### Variations

Variations are specified within a dictionary. The key will be the attribute referencing the resized image.
A variation can be defined both as a tuple or a dictionary.

Example:

```python
from django.db import models
from stdimage import StdImageField, JPEGField


class MyModel(models.Model):
    # works just like django's ImageField
    image = StdImageField(upload_to='path/to/img')

    # creates a thumbnail resized to maximum size to fit a 100x75 area
    image = StdImageField(upload_to='path/to/img',
                          variations={'thumbnail': {'width': 100, 'height': 75}})

    # is the same as dictionary-style call
    image = StdImageField(upload_to='path/to/img', variations={'thumbnail': (100, 75)})

    # JPEGField variations are converted to JPEGs.
    jpeg = JPEGField(
        upload_to='path/to/img',
        variations={'full': (None, None), 'thumbnail': (100, 75)},
    )

    # creates a thumbnail resized to 100x100 croping if necessary
    image = StdImageField(upload_to='path/to/img', variations={
        'thumbnail': {"width": 100, "height": 100, "crop": True}
    })

    ## Full ammo here. Please note all the definitions below are equal
    image = StdImageField(upload_to='path/to/img', blank=True, variations={
        'large': (600, 400),
        'thumbnail': (100, 100, True),
        'medium': (300, 200),
    }, delete_orphans=True)
```

To use these variations in templates use `myimagefield.variation_name`.

Example:

```html
<a href="{{ object.myimage.url }}"><img alt="" src="{{ object.myimage.thumbnail.url }}"/></a>
```

### Upload to function

You can use a function for the `upload_to` argument. Using [Django Dynamic Filenames][dynamic_filenames].[dynamic_filenames]: https://github.com/codingjoe/django-dynamic-filenames

This allows images to be given unique paths and filenames based on the model instance.

Example

```python
from django.db import models
from stdimage import StdImageField
from dynamic_filenames import FilePattern

upload_to_pattern = FilePattern(
    filename_pattern='my_model/{app_label:.25}/{model_name:.30}/{uuid:base32}{ext}',
)


class MyModel(models.Model):
    # works just like django's ImageField
    image = StdImageField(upload_to=upload_to_pattern)
```

### Validators
The `StdImageField` doesn't implement any size validation out-of-the-box.
However, Validation can be specified using the validator attribute
and using a set of validators shipped with this package.
Validators can be used for both Forms and Models.

Example

```python
from django.db import models
from stdimage.validators import MinSizeValidator, MaxSizeValidator
from stdimage.models import StdImageField


class MyClass(models.Model):
    image1 = StdImageField(validators=[MinSizeValidator(800, 600)])
    image2 = StdImageField(validators=[MaxSizeValidator(1028, 768)])
```

**CAUTION:** The MaxSizeValidator should be used with caution.
As storage isn't expensive, you shouldn't restrict upload dimensions.
If you seek prevent users form overflowing your memory you should restrict the HTTP upload body size.

### Deleting images

Django [dropped support](https://docs.djangoproject.com/en/dev/releases/1.3/#deleting-a-model-doesn-t-delete-associated-files)
for automated deletions in version 1.3.

Since version 5, this package supports a `delete_orphans` argument. It will delete
orphaned files, should a file be deleted or replaced via a Django form and the object with
the `StdImageField` be deleted. It will not delete files if the field value is changed or
reassigned programatically. In these rare cases, you will need to handle proper deletion
yourself.

```python
from django.db import models
from stdimage.models import StdImageField


class MyModel(models.Model):
    image = StdImageField(
        upload_to='path/to/files',
        variations={'thumbnail': (100, 75)},
        delete_orphans=True,
        blank=True,
    )
```

### Async image processing
Tools like celery allow to execute time-consuming tasks outside of the request. If you don't want
to wait for your variations to be rendered in request, StdImage provides you the option to pass an
async keyword and a 'render_variations' function that triggers the async task.
Note that the callback is not transaction save, but the file variations will be present.
The example below is based on celery.

`tasks.py`:
```python
from django.apps import apps

from celery import shared_task

from stdimage.utils import render_variations


@shared_task
def process_photo_image(file_name, variations, storage):
    render_variations(file_name, variations, replace=True, storage=storage)
    obj = apps.get_model('myapp', 'Photo').objects.get(image=file_name)
    obj.processed = True
    obj.save()
```

`models.py`:
```python
from django.db import models
from stdimage.models import StdImageField

from .tasks import process_photo_image

def image_processor(file_name, variations, storage):
    process_photo_image.delay(file_name, variations, storage)
    return False  # prevent default rendering

class AsyncImageModel(models.Model):
    image = StdImageField(
        # above task definition can only handle one model object per image filename
        upload_to='path/to/file/', # or use a function
        render_variations=image_processor  # pass boolean or callable
    )
    processed = models.BooleanField(default=False)  # flag that could be used for view querysets
```

### Re-rendering variations
You might have added or changed variations to an existing field. That means you will need to render new variations.
This can be accomplished using a management command.
```bash
python manage.py rendervariations 'app_name.model_name.field_name' [--replace] [-i/--ignore-missing]
```
The `replace` option will replace all existing files.
The `ignore-missing` option will suspend 'missing source file' errors and keep
rendering variations for other files. Otherwise, the command will stop on first missing file.

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/codingjoe/django-stdimage",
    "name": "django-stdimage",
    "maintainer": "",
    "docs_url": null,
    "requires_python": "",
    "maintainer_email": "",
    "keywords": "",
    "author": "Johannes Hoppe",
    "author_email": "info@johanneshoppe.com",
    "download_url": "https://files.pythonhosted.org/packages/f9/65/dcc72a467addf3f78923eb7510cf8dc36e6c41f03422217641f39c5578de/django-stdimage-6.0.2.tar.gz",
    "platform": null,
    "description": "[![version](https://img.shields.io/pypi/v/django-stdimage.svg)](https://pypi.python.org/pypi/django-stdimage/)\n[![codecov](https://codecov.io/gh/codingjoe/django-stdimage/branch/master/graph/badge.svg)](https://codecov.io/gh/codingjoe/django-stdimage)\n[![MIT License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)\n\n# Django Standardized Image Field\n\nThis package has been deprecated in favor of [django-pictures][django-pictures].\n\n## Migration Instructions\n\nFirst, make sure you understand the differences between the two packages and\nhow to serve images in a modern web application via the [picture][picture-tag]-Element.\n\nNext, follow the setup instructions for [django-pictures][django-pictures].\n\nOnce you are set up, change your models to use the new `PictureField` and provide the\n `aspect_ratios` you'd like to serve. Do create migrations just yet.\n\nThis step should be followed by changing your templates and frontend.\nThe new placeholders feature for local development should help you\nto do this almost effortlessly.\n\nFinally, run `makemigrations` and replace the `AlterField` operation with\n`AlterPictureField`.\n\nWe highly recommend to use Django's `image_width` and `image_height` fields, to avoid\nunnecessary IO. If you can add these fields to your model, you can use the following\nsnippet to populate them:\n\n```python\nimport django.core.files.storage\nfrom django.db import migrations, models\nimport pictures.models\nfrom pictures.migrations import AlterPictureField\n\ndef forward(apps, schema_editor):\n    for obj in apps.get_model(\"my-app.MyModel\").objects.all().iterator():\n        obj.image_width = obj.logo.width\n        obj.image_height = obj.logo.height\n        obj.save(update_fields=[\"image_height\", \"image_width\"])\n\ndef backward(apps, schema_editor):\n    apps.get_model(\"my-app.MyModel\").objects.all().update(\n        image_width=None,\n        image_height=None,\n    )\n\nclass Migration(migrations.Migration):\n    dependencies = [\n        ('my-app', '0001_initial'),\n    ]\n\n    operations = [\n        migrations.AddField(\n            model_name=\"mymodel\",\n            name=\"image_height\",\n            field=models.PositiveIntegerField(editable=False, null=True),\n        ),\n        migrations.AddField(\n            model_name=\"mymodel\",\n            name=\"image_width\",\n            field=models.PositiveIntegerField(editable=False, null=True),\n        ),\n        migrations.RunPython(forward, backward),\n        AlterPictureField(\n            model_name=\"mymodel\",\n            name=\"image\",\n            field=pictures.models.PictureField(\n                aspect_ratios=[\"3/2\", \"3/1\"],\n                breakpoints={\"desktop\": 1024, \"mobile\": 576},\n                container_width=1200,\n                file_types=[\"WEBP\"],\n                grid_columns=12,\n                height_field=\"image_height\",\n                pixel_densities=[1, 2],\n                storage=django.core.files.storage.FileSystemStorage(),\n                upload_to=\"pictures/\",\n                verbose_name=\"image\",\n                width_field=\"image_width\",\n            ),\n        ),\n    ]\n```\n\n[django-pictures]: https://github.com/codingjoe/django-pictures\n[picture-tag]: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/picture\n\n## Why would I want this?\n\nThis is a drop-in replacement for the [Django ImageField](https://docs.djangoproject.com/en/1.8/ref/models/fields/#django.db.models.ImageField) that provides a standardized way to handle image uploads.\nIt is designed to be as easy to use as possible, and to provide a consistent interface for all image fields.\nIt allows images to be presented in various size variants (eg:thumbnails, mid, and hi-res versions)\nand it provides a way to handle images that are too large with validators.\n\n\n## Features\n\nDjango Standardized Image Field implements the following features:\n\n* [Django-Storages](https://django-storages.readthedocs.io/en/latest/) compatible (eg: S3, Azure, Google Cloud Storage, etc)\n* Resizes images to different sizes\n* Access thumbnails on model level, no template tags required\n* Preserves original images\n* Can be rendered asynchronously (ie as a [Celery job](https://realpython.com/asynchronous-tasks-with-django-and-celery/))\n* Restricts acceptable image dimensions\n* Renames a file to a standardized name format (using a callable `upload_to` function, see below)\n\n## Installation\n\nSimply install the latest stable package using the following command:\n\n```bash\npip install django-stdimage\n# or\npipenv install django-stdimage\n```\n\nand add `'stdimage'` to `INSTALLED_APP`s in your settings.py, that's it!\n\n## Usage\n\nNow it's instally you can use either: `StdImageField` or `JPEGField`.\n\n`StdImageField` works just like Django's own\n[ImageField](https://docs.djangoproject.com/en/dev/ref/models/fields/#imagefield)\nexcept that you can specify different size variations.\n\nThe `JPEGField` is identical to the `StdImageField` but all images are\nconverted to JPEGs, no matter what type the original file is.\n\n### Variations\n\nVariations are specified within a dictionary. The key will be the attribute referencing the resized image.\nA variation can be defined both as a tuple or a dictionary.\n\nExample:\n\n```python\nfrom django.db import models\nfrom stdimage import StdImageField, JPEGField\n\n\nclass MyModel(models.Model):\n    # works just like django's ImageField\n    image = StdImageField(upload_to='path/to/img')\n\n    # creates a thumbnail resized to maximum size to fit a 100x75 area\n    image = StdImageField(upload_to='path/to/img',\n                          variations={'thumbnail': {'width': 100, 'height': 75}})\n\n    # is the same as dictionary-style call\n    image = StdImageField(upload_to='path/to/img', variations={'thumbnail': (100, 75)})\n\n    # JPEGField variations are converted to JPEGs.\n    jpeg = JPEGField(\n        upload_to='path/to/img',\n        variations={'full': (None, None), 'thumbnail': (100, 75)},\n    )\n\n    # creates a thumbnail resized to 100x100 croping if necessary\n    image = StdImageField(upload_to='path/to/img', variations={\n        'thumbnail': {\"width\": 100, \"height\": 100, \"crop\": True}\n    })\n\n    ## Full ammo here. Please note all the definitions below are equal\n    image = StdImageField(upload_to='path/to/img', blank=True, variations={\n        'large': (600, 400),\n        'thumbnail': (100, 100, True),\n        'medium': (300, 200),\n    }, delete_orphans=True)\n```\n\nTo use these variations in templates use `myimagefield.variation_name`.\n\nExample:\n\n```html\n<a href=\"{{ object.myimage.url }}\"><img alt=\"\" src=\"{{ object.myimage.thumbnail.url }}\"/></a>\n```\n\n### Upload to function\n\nYou can use a function for the `upload_to` argument. Using [Django Dynamic Filenames][dynamic_filenames].[dynamic_filenames]: https://github.com/codingjoe/django-dynamic-filenames\n\nThis allows images to be given unique paths and filenames based on the model instance.\n\nExample\n\n```python\nfrom django.db import models\nfrom stdimage import StdImageField\nfrom dynamic_filenames import FilePattern\n\nupload_to_pattern = FilePattern(\n    filename_pattern='my_model/{app_label:.25}/{model_name:.30}/{uuid:base32}{ext}',\n)\n\n\nclass MyModel(models.Model):\n    # works just like django's ImageField\n    image = StdImageField(upload_to=upload_to_pattern)\n```\n\n### Validators\nThe `StdImageField` doesn't implement any size validation out-of-the-box.\nHowever, Validation can be specified using the validator attribute\nand using a set of validators shipped with this package.\nValidators can be used for both Forms and Models.\n\nExample\n\n```python\nfrom django.db import models\nfrom stdimage.validators import MinSizeValidator, MaxSizeValidator\nfrom stdimage.models import StdImageField\n\n\nclass MyClass(models.Model):\n    image1 = StdImageField(validators=[MinSizeValidator(800, 600)])\n    image2 = StdImageField(validators=[MaxSizeValidator(1028, 768)])\n```\n\n**CAUTION:** The MaxSizeValidator should be used with caution.\nAs storage isn't expensive, you shouldn't restrict upload dimensions.\nIf you seek prevent users form overflowing your memory you should restrict the HTTP upload body size.\n\n### Deleting images\n\nDjango [dropped support](https://docs.djangoproject.com/en/dev/releases/1.3/#deleting-a-model-doesn-t-delete-associated-files)\nfor automated deletions in version 1.3.\n\nSince version 5, this package supports a `delete_orphans` argument. It will delete\norphaned files, should a file be deleted or replaced via a Django form and the object with\nthe `StdImageField` be deleted. It will not delete files if the field value is changed or\nreassigned programatically. In these rare cases, you will need to handle proper deletion\nyourself.\n\n```python\nfrom django.db import models\nfrom stdimage.models import StdImageField\n\n\nclass MyModel(models.Model):\n    image = StdImageField(\n        upload_to='path/to/files',\n        variations={'thumbnail': (100, 75)},\n        delete_orphans=True,\n        blank=True,\n    )\n```\n\n### Async image processing\nTools like celery allow to execute time-consuming tasks outside of the request. If you don't want\nto wait for your variations to be rendered in request, StdImage provides you the option to pass an\nasync keyword and a 'render_variations' function that triggers the async task.\nNote that the callback is not transaction save, but the file variations will be present.\nThe example below is based on celery.\n\n`tasks.py`:\n```python\nfrom django.apps import apps\n\nfrom celery import shared_task\n\nfrom stdimage.utils import render_variations\n\n\n@shared_task\ndef process_photo_image(file_name, variations, storage):\n    render_variations(file_name, variations, replace=True, storage=storage)\n    obj = apps.get_model('myapp', 'Photo').objects.get(image=file_name)\n    obj.processed = True\n    obj.save()\n```\n\n`models.py`:\n```python\nfrom django.db import models\nfrom stdimage.models import StdImageField\n\nfrom .tasks import process_photo_image\n\ndef image_processor(file_name, variations, storage):\n    process_photo_image.delay(file_name, variations, storage)\n    return False  # prevent default rendering\n\nclass AsyncImageModel(models.Model):\n    image = StdImageField(\n        # above task definition can only handle one model object per image filename\n        upload_to='path/to/file/', # or use a function\n        render_variations=image_processor  # pass boolean or callable\n    )\n    processed = models.BooleanField(default=False)  # flag that could be used for view querysets\n```\n\n### Re-rendering variations\nYou might have added or changed variations to an existing field. That means you will need to render new variations.\nThis can be accomplished using a management command.\n```bash\npython manage.py rendervariations 'app_name.model_name.field_name' [--replace] [-i/--ignore-missing]\n```\nThe `replace` option will replace all existing files.\nThe `ignore-missing` option will suspend 'missing source file' errors and keep\nrendering variations for other files. Otherwise, the command will stop on first missing file.\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Django Standarized Image Field",
    "version": "6.0.2",
    "project_urls": {
        "Homepage": "https://github.com/codingjoe/django-stdimage"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "15e4f90e895cb97bd625c9d162dc7919addd6321d34023439623abb6e4c99f30",
                "md5": "deff739d4701d1369ded2d772a39b787",
                "sha256": "9a73f7da48c48074580e2b032d5bdb7164935dbe4b9dc4fb88a7e112f3d521c8"
            },
            "downloads": -1,
            "filename": "django_stdimage-6.0.2-py2.py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "deff739d4701d1369ded2d772a39b787",
            "packagetype": "bdist_wheel",
            "python_version": "py2.py3",
            "requires_python": null,
            "size": 19265,
            "upload_time": "2023-11-06T17:26:44",
            "upload_time_iso_8601": "2023-11-06T17:26:44.908021Z",
            "url": "https://files.pythonhosted.org/packages/15/e4/f90e895cb97bd625c9d162dc7919addd6321d34023439623abb6e4c99f30/django_stdimage-6.0.2-py2.py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "f965dcc72a467addf3f78923eb7510cf8dc36e6c41f03422217641f39c5578de",
                "md5": "857058370f5d4e1b12ed606ba4474b1d",
                "sha256": "880ab14828be56b53f711c3afae83c219ddd5d9af00850626736feb48382bf7f"
            },
            "downloads": -1,
            "filename": "django-stdimage-6.0.2.tar.gz",
            "has_sig": false,
            "md5_digest": "857058370f5d4e1b12ed606ba4474b1d",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 14961,
            "upload_time": "2023-11-06T17:26:46",
            "upload_time_iso_8601": "2023-11-06T17:26:46.737205Z",
            "url": "https://files.pythonhosted.org/packages/f9/65/dcc72a467addf3f78923eb7510cf8dc36e6c41f03422217641f39c5578de/django-stdimage-6.0.2.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-11-06 17:26:46",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "codingjoe",
    "github_project": "django-stdimage",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "django-stdimage"
}
        
Elapsed time: 0.14914s