django-stdimage2


Namedjango-stdimage2 JSON
Version 0.1.13 PyPI version JSON
download
home_pagehttps://github.com/codingjoe/django-stdimage2
SummaryDjango Standarized Image Field
upload_time2023-07-07 07:42:54
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-stdimage2.svg)](https://pypi.python.org/pypi/django-stdimage/) -->
<!-- [![codecov](https://codecov.io/gh/codingjoe/django-stdimage2/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 2

## 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-stdimage2
# or
pipenv install django-stdimage2
``` -->
``` bash
pip install git+https://github.com/igorkhaylov/django-stdimage2.git
```
and add `'stdimage2'` 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 stdimage2 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 stdimage2 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 stdimage2.validators import MinSizeValidator, MaxSizeValidator
from stdimage2.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 stdimage2.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, StdImage2 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 stdimage2.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 stdimage2.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 rendervariations2 '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-stdimage2",
    "name": "django-stdimage2",
    "maintainer": "",
    "docs_url": null,
    "requires_python": "",
    "maintainer_email": "",
    "keywords": "",
    "author": "Johannes Hoppe",
    "author_email": "info@johanneshoppe.com",
    "download_url": "https://files.pythonhosted.org/packages/48/02/56eef8642ed71b5358a6ea668ca34401c7b055f268d098ef326c89570c76/django-stdimage2-0.1.13.tar.gz",
    "platform": null,
    "description": "<!-- [![version](https://img.shields.io/pypi/v/django-stdimage2.svg)](https://pypi.python.org/pypi/django-stdimage/) -->\n<!-- [![codecov](https://codecov.io/gh/codingjoe/django-stdimage2/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 2\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-stdimage2\n# or\npipenv install django-stdimage2\n``` -->\n``` bash\npip install git+https://github.com/igorkhaylov/django-stdimage2.git\n```\nand add `'stdimage2'` 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 stdimage2 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 stdimage2 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 stdimage2.validators import MinSizeValidator, MaxSizeValidator\nfrom stdimage2.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 stdimage2.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, StdImage2 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 stdimage2.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 stdimage2.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 rendervariations2 '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\n\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Django Standarized Image Field",
    "version": "0.1.13",
    "project_urls": {
        "Homepage": "https://github.com/codingjoe/django-stdimage2"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "480256eef8642ed71b5358a6ea668ca34401c7b055f268d098ef326c89570c76",
                "md5": "05d1685237733a9a43d980b2bf34685d",
                "sha256": "1d68cb3cd763a8d35f4a97c94ceb84b94cf807e3e3a849f6659379db28f3a2f9"
            },
            "downloads": -1,
            "filename": "django-stdimage2-0.1.13.tar.gz",
            "has_sig": false,
            "md5_digest": "05d1685237733a9a43d980b2bf34685d",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 14098,
            "upload_time": "2023-07-07T07:42:54",
            "upload_time_iso_8601": "2023-07-07T07:42:54.713608Z",
            "url": "https://files.pythonhosted.org/packages/48/02/56eef8642ed71b5358a6ea668ca34401c7b055f268d098ef326c89570c76/django-stdimage2-0.1.13.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-07-07 07:42:54",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "codingjoe",
    "github_project": "django-stdimage2",
    "github_not_found": true,
    "lcname": "django-stdimage2"
}
        
Elapsed time: 0.18842s