{"id":13814044,"url":"https://github.com/codingjoe/django-stdimage","last_synced_at":"2025-05-15T03:32:34.409Z","repository":{"id":12643132,"uuid":"15314657","full_name":"codingjoe/django-stdimage","owner":"codingjoe","description":"Django Standardized Image Field","archived":false,"fork":true,"pushed_at":"2024-04-26T21:55:58.000Z","size":529,"stargazers_count":259,"open_issues_count":8,"forks_count":64,"subscribers_count":8,"default_branch":"master","last_synced_at":"2024-05-22T15:11:16.118Z","etag":null,"topics":["django","image","image-processing","python","thumbnails"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":"xarg/django-stdimage","license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/codingjoe.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":"FUNDING.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null},"funding":{"github":"codingjoe","custom":"https://www.paypal.me/codingjoe"}},"created_at":"2013-12-19T15:08:05.000Z","updated_at":"2024-04-12T09:16:18.000Z","dependencies_parsed_at":"2023-02-10T14:01:07.020Z","dependency_job_id":null,"html_url":"https://github.com/codingjoe/django-stdimage","commit_stats":{"total_commits":395,"total_committers":45,"mean_commits":8.777777777777779,"dds":"0.49367088607594933","last_synced_commit":"17e45ed2167901d2fc2a48f4a557a8c326d17031"},"previous_names":[],"tags_count":41,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/codingjoe%2Fdjango-stdimage","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/codingjoe%2Fdjango-stdimage/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/codingjoe%2Fdjango-stdimage/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/codingjoe%2Fdjango-stdimage/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/codingjoe","download_url":"https://codeload.github.com/codingjoe/django-stdimage/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":225326412,"owners_count":17456936,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["django","image","image-processing","python","thumbnails"],"created_at":"2024-08-04T04:01:41.050Z","updated_at":"2024-11-19T09:30:19.639Z","avatar_url":"https://github.com/codingjoe.png","language":"Python","funding_links":["https://github.com/sponsors/codingjoe","https://www.paypal.me/codingjoe"],"categories":["Python"],"sub_categories":[],"readme":"[![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\u003ca href=\"{{ object.myimage.url }}\"\u003e\u003cimg alt=\"\" src=\"{{ object.myimage.thumbnail.url }}\"/\u003e\u003c/a\u003e\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","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcodingjoe%2Fdjango-stdimage","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fcodingjoe%2Fdjango-stdimage","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcodingjoe%2Fdjango-stdimage/lists"}