Code Monkey home page Code Monkey logo

django-stdimage's Introduction

version codecov MIT License

Django Standardized Image Field

This package has been deprecated in favor of 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-Element.

Next, follow the setup instructions for 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:

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",
            ),
        ),
    ]

Why would I want this?

This is a drop-in replacement for the Django 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 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)
  • 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:

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

and add 'stdimage' to INSTALLED_APPs 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 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:

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:

<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

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

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 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.

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:

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:

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.

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.

django-stdimage's People

Contributors

5p4k avatar amureki avatar anih avatar chaosk avatar codingjoe avatar dependabot[bot] avatar georgewhewell avatar gitter-badger avatar hcarvalhoalves avatar jeromelebleu avatar jmsmkn avatar jordifierro avatar julzhk avatar katomaso avatar lraphael avatar m4l avatar marojenka avatar martinmaillard avatar mazzly avatar mcnemesis avatar mitja avatar mthaddon avatar oalsing avatar pyup-bot avatar requires avatar rhenter avatar tomscytale avatar vchrisb avatar vosi avatar vshab avatar

Stargazers

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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

django-stdimage's Issues

UploadToUUID generating the same uuid for every upload

class UploadToUUID(UploadTo):

    def __init__(self, **kwargs):
        kwargs.update({
            'name': uuid.uuid4().hex,
        })
        super(UploadToUUID, self).__init__(**kwargs)

Shouldn't the name update be in the call and not the init? Otherwise, you'll just end up naming the file to the same uuid with the object instantiated with a default name.

Image pathes on Windows

Hello.

I have an issue with image pathes on windows os. Image pathes are incorrect:

images\8bf1763f53834fb4be962f416a51e2b9.index.jpg

i.e. variation name is jointed by os.path.sep which is wrong for my os.

Windows does not support resource module

While django-stdimage works very well in general, rendervariations breaks due to ModuleNotFoundError.

File "C:\path\to\env\lib\site-packages\stdimage\management\commands\rendervariations.py", line 4, in <module>
ModuleNotFoundError: No module named 'resource'

It's probably not a big issue if memory usage would just say n/a on Windows, and wrap the import in try except? If this sounds like a good idea, I could do a pull request.

"crop": True fails in Python 3.4

Great package! However, when prototyping using it in Python 3.4 on this code:

    image = StdImageField(
        upload_to=upload_to, null=True, blank=True,
        variations={'thumbnail': {'with': 64, 'height': 64, 'crop': True}}
    )

I received this particular error:

[01/Aug/2015 18:05:29]"GET /cheeses/monterey-jack/update/ HTTP/1.1" 200 26223
Internal Server Error: /cheeses/monterey-jack/upload/
Traceback (most recent call last):
  File "/Users/danny/projects/envs/everycheese/lib/python3.4/site-packages/django/core/handlers/base.py", line 132, in get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/contextlib.py", line 30, in inner
    return func(*args, **kwds)
  File "/Users/danny/projects/envs/everycheese/lib/python3.4/site-packages/django/views/generic/base.py", line 71, in view
    return self.dispatch(request, *args, **kwargs)
  File "/Users/danny/projects/envs/everycheese/lib/python3.4/site-packages/django/views/generic/base.py", line 89, in dispatch
    return handler(request, *args, **kwargs)
  File "/Users/danny/projects/envs/everycheese/lib/python3.4/site-packages/django/views/generic/edit.py", line 272, in post
    return super(BaseUpdateView, self).post(request, *args, **kwargs)
  File "/Users/danny/projects/envs/everycheese/lib/python3.4/site-packages/django/views/generic/edit.py", line 215, in post
    return self.form_valid(form)
  File "/Users/danny/projects/everycheese/everycheese/cheeses/views.py", line 40, in form_valid
    self.object = form.save()
  File "/Users/danny/projects/envs/everycheese/lib/python3.4/site-packages/django/forms/models.py", line 463, in save
    construct=False)
  File "/Users/danny/projects/envs/everycheese/lib/python3.4/site-packages/django/forms/models.py", line 105, in save_instance
    instance.save()
  File "/Users/danny/projects/envs/everycheese/lib/python3.4/site-packages/django/db/models/base.py", line 710, in save
    force_update=force_update, update_fields=update_fields)
  File "/Users/danny/projects/envs/everycheese/lib/python3.4/site-packages/django/db/models/base.py", line 738, in save_base
    updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
  File "/Users/danny/projects/envs/everycheese/lib/python3.4/site-packages/django/db/models/base.py", line 800, in _save_table
    for f in non_pks]
  File "/Users/danny/projects/envs/everycheese/lib/python3.4/site-packages/django/db/models/base.py", line 800, in <listcomp>
    for f in non_pks]
  File "/Users/danny/projects/envs/everycheese/lib/python3.4/site-packages/django/db/models/fields/files.py", line 315, in pre_save
    file.save(file.name, file, save=False)
  File "/Users/danny/projects/envs/everycheese/lib/python3.4/site-packages/stdimage/models.py", line 49, in save
    self.render_variations()
  File "/Users/danny/projects/envs/everycheese/lib/python3.4/site-packages/stdimage/models.py", line 59, in render_variations
    self.render_variation(self.name, variation, replace, self.storage)
  File "/Users/danny/projects/envs/everycheese/lib/python3.4/site-packages/stdimage/models.py", line 98, in render_variation
    method=resample
  File "/Users/danny/projects/envs/everycheese/lib/python3.4/site-packages/PIL/ImageOps.py", line 334, in fit
    return out.resize(size, method)
  File "/Users/danny/projects/envs/everycheese/lib/python3.4/site-packages/PIL/Image.py", line 1569, in resize
    return self._new(self.im.resize(size, resample))
TypeError: integer argument expected, got float

As soon as I removed 'crop': True it started to work again.

Get all variations in serializer

I have a REST API, and would like to get all variations.

Right now I only get
"picture": "/media/pictures/f80032bde14c4040bb1d24c270c5ad45.png",
which is the original, but I would like to get all variations in the response as well (large, medium, thumbnail). How would I get that with a serializer?

Cannot add attribute to stdimage widget

I just found that I cannot add class attribute to stdimage widget.

I want to render the widget like this:

Photo:


<input class="form-control" id="id_photo" name="photo" type="file">

Variations attributes not preserved if object is saved in Django cache

Hi,
I'm using django-stdimage version 2.0.6. Consider the following example:

class Photo(models.Model):
    image = StdImageField(upload_to='photos', variations={
        'thumbnail': (500, 500),
    })

In a view I retrieve a Photo object and I want to cache it using default Django in-memory cache.

from django.core.cache import caches

cache = caches['default']
today_photo = cache.get('today_photo')
if today_photo is None:
    # Photo object not found in cache
    # retrieve it with some query
    today_photo = Photo.objects.filter(...)
    cache.set('today_photo', today_photo, 300)
    # this correctly logs the url of the thumbnail
    logger.debug('today_photo thumbnail: %s' % today_photo.image.thumbnail)
else:
    # Photo object is taken from cache
    # this is a server error: 'StdImageFieldFile' object has no attribute 'thumbnail'
    logger.debug('today_photo thumbnail: %s' % today_photo.image.thumbnail)

When retrieved from cache, the image field "lost" the thumbnail attribute. Is it a limitation of what can be saved in django cache or is it an issue you can address?

Thank you very much for your work!

add in fill option instead of crop

I was wondering if you could add in a fill option instead of crop for the variations rendering. Concept would be for odd resolutions to white fill instead of altering the aspect ratio.

I believe the algorithm would be... apologies... little sleep last night.

shrink width, and height until they're <= the variation. then for anything that's < variation you expand with a white border until you are >= the variation. Then crop to the exact variation. That should keep the entire image in, keep the aspect resolution, and replace anything else with whitefill

while img.size[0] > variation['width'] or img.size[1] > variation['height']:
                    width = img.size[0]
                    height = img.size[1]

                    if width > variation['width']:
                        factor = width / variation['width']

                        img.thumbnail((int(variation['width']), 
                                       int(height * factor)), resample=resample)

                    elif height > variation['height']:
                        factor = height / variation['height']

                        img.thumbnail((int(width * factor),
                                       int(variation['height']), resample=resample)

while img.size[0] < variation['width'] or img.size[1] < variation['height']:    
                    width = img.size[0]
                    height = img.size[1]

                    if width < variation['width']:
                        border = variation['width'] - width

                        img = ImageOps.expand(img, border, 1)

                    elif height < variation['height']:
                        border = variation['height'] - height

                        img = ImageOps.expand(img, border, 1)

img = ImageOps.fit(img, (variation['width'], variation['height']), method=resample)

`UploadTo` utils break when the original filename does not have an extension

https://github.com/codingjoe/django-stdimage/blob/master/stdimage/utils.py#L17
In this code part

def __call__(self, instance, filename):
    defaults = {
        'ext': filename.rsplit('.', 1)[1],
        'name': filename.rsplit('.', 1)[0],
        'path': filename.rsplit('/', 1)[0],
        'class_name': instance.__class__.__name__,
    }
    defaults.update(self.kwargs)
    return os.path.join(self.path_pattern % defaults, self.file_pattern % defaults).lower()

I'm quite certain we should replace the .rsplit usages with os.path.split and os.path.splitext

stdimage and south

Hello!

I have django 1.6.2 and django-stdimage 0.5.1. My model:

class Model1(models.Model):
    title = models.CharField("Title", max_length=255)
    photo = StdImageField("Photo", upload_to='photos', variations={'thumbnail': (100, 75), 'large': (640, 480)}, blank=True,)

Try to create initial migrate and get AttributeError: 'StdImageField' object has no attribute 'size'.

If I comment this lines

            #"size": ["size", {"default": None}],
            #"thumbnail_size": ["thumbnail_size", {"default": None}],

in stdimage/__init__.py migration will be created.

Specifying width / height fields is incompatible with MinSizeValidator

Given the following definition:

image = StdImageField(
    upload_to='somewhere',
    height_field='height',
    width_field='width',
    validators=[MinSizeValidator(600, 300)],
    variations={'thumb': {'width': 600, 'height': 300, 'crop': True}}
)

The following exception occurs upon validation in the Django admin:

... irrelevant frames omitted
File "/path/to/django/forms/forms.py", line 153, in errors
  self.full_clean()
File "/path/to/django/forms/forms.py", line 364, in full_clean
  self._post_clean()
File "/path/to/django/forms/models.py", line 396, in _post_clean
  self.instance.full_clean(exclude=exclude, validate_unique=False)
File "/path/to/django/db/models/base.py", line 1122, in full_clean
  self.clean_fields(exclude=exclude)
File "/path/to/django/db/models/base.py", line 1164, in clean_fields
  setattr(self, f.attname, f.clean(raw_value, self))
File "/path/to/django/db/models/fields/__init__.py", line 600, in clean
  self.run_validators(value)
File "/path/to/django/db/models/fields/__init__.py", line 552, in run_validators
  v(value)
File "/path/to/stdimage/validators.py", line 22, in __call__
  cleaned = self.clean(value)
File "/path/to/stdimage/validators.py", line 32, in clean
  value.seek(0)

I'm not entirely certain of the upstream control flow before this point, and why the file would be closed.

Environment

  • OS X 10.11.4
  • Python 3.5.1
  • django==1.9.5
  • pillow==3.2.0
  • django-stdimage==2.3.2

No module named 'cStringIO'

When i am trying to use this plugin, i got this import problem. I am using Python 3.3, Django 1.6 a windows 8.1. This error is even when i just add this plugin to settings.
P.S.: sorry for my english
P.S. i did some research and its because cstring modelu is no longer in Python3. Can you fix it?

rendervariations doesn't use custom render_variations

Hello!

When rerender variations through python manage.py rendervariations 'app_name.model_name.field_name' --replace stdimage use built-in render_variation function skipping render_variations parameter from StdImageField.

How to reproduce:

  1. Create the field in the model with custom render_variations function.
  2. Create model instance.
  3. Check result variations.
  4. Run python manage.py rendervariations 'app_name.model_name.field_name' --replace
  5. Result variations will be rendered with render_variation from StdImageFieldFile not with function from 1.

Mistake in documentation

Hello!

Some mistakes in documentation at following string

`

creates a thumbnail resized to 100x100 croping if necessary and excepts only image greater than 1920x1080px

image5 = StdImageField(upload_to='path/to/img', variations={'thumbnail': (100, 100, True}, min_size(1920,1080))

`

Look at {'thumbnail': (100, 100, True)} and min_size=(1920,1080). You missed ) after True and = after min_size.

Initial Update

Hi ๐Ÿ‘Š

This is my first visit to this fine repo, but it seems you have been working hard to keep all dependencies updated so far.

Once you have closed this issue, I'll create seperate pull requests for every update as soon as I find one.

That's it for now!

Happy merging! ๐Ÿค–

populate_from get value from a method

Hi,

Its there a way to get filename generated by multiple fields or by method call ?

Something like this:

class Seller(models.Model):    
    company_name    = models.CharField(db_column="company_name", max_length=200)
    ...    
    logo = StdImageField(        
        upload_to=UploadToAutoSlug(name='image', path='images/logos', populate_from='seller_logo'),        
        render_variations=False  # pass boolean or callable
    )

    def seller_logo(self):
        return str(self.company_name + '_logo')

doing this i get this filename: bound-method-sellerseller_logo-of-seller-seller-object.png

and i need something like this: company_name_logo.png

Thanks in Advance

Management Command "rendervariations" throws an AttributeError with Current Version of progressbar2 (3.3.0)

Looks like they did a major re-factor of the progressbar2 app, and the class referenced no longer exists. See: https://github.com/WoLpH/python-progressbar/blob/develop/progressbar/widgets.py

Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/home/django/domains/mydomain.com/lib/python3.4/site-packages/django/core/management/__init__.py", line 351, in execute_from_command_line
    utility.execute()
  File "/home/django/domains/mydomain.com/lib/python3.4/site-packages/django/core/management/__init__.py", line 343, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/django/domains/mydomain.com/lib/python3.4/site-packages/django/core/management/__init__.py", line 190, in fetch_command
    klass = load_command_class(app_name, subcommand)
  File "/home/django/domains/mydomain.com/lib/python3.4/site-packages/django/core/management/__init__.py", line 40, in load_command_class
    module = import_module('%s.management.commands.%s' % (app_name, name))
  File "/usr/local/lib/python3.4/importlib/__init__.py", line 109, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 2254, in _gcd_import
  File "<frozen importlib._bootstrap>", line 2237, in _find_and_load
  File "<frozen importlib._bootstrap>", line 2226, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 1200, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 1129, in _exec
  File "<frozen importlib._bootstrap>", line 1471, in exec_module
  File "<frozen importlib._bootstrap>", line 321, in _call_with_frames_removed
  File "/home/django/domains/mydomain.com/lib/python3.4/site-packages/stdimage/management/commands/rendervariations.py", line 19, in <module>
    class MemoryUsageWidget(progressbar.widgets.Widget):
AttributeError: 'module' object has no attribute 'Widget'

S3BotoStorage import error on rendervarations

Running the rendervariations command with S3BotoStorage as storage backend gives the following error:

ImportError: Module "django.core.files.storage" does not define a "S3BotoStorage" attribute/class

I'm on django 1.9.2 with django-storages-redux 1.4, python 1.3.5 and the current master of django-stdimage.

On inspection it seems the field.storage object in the render function in stdimage/management/commands/rendervariations.py prints as <storages.backends.s3boto.S3BotoStorage object at 0x102f69550>, but the __module__ is django.core.files.storage.

The class_to_path function returns 'django.core.files.storage.S3BotoStorage' when the actual class is located at 'storages.backends.s3boto.S3BotoStorage'.

Any idea what is going wrong here?

Travis-CI

Add travis-ci testing to ensure better builds.

rendervariations command fails when custom manager is defined on abstract model

django-stdimage==2.0.0
django==1.8

class CustomManager(models.Manager):
    pass

class BaseModel(models.Model):
    custom_objects = CustomManager()

    class Meta:
        abstract = True

class MyModel(BaseModel):
    image = StdImageField(...)

$ python manage.py rendervariations 'app.MyModel.image'
AttributeError: type object 'MyModel' has no attribute 'objects'

You should replace this line https://github.com/codingjoe/django-stdimage/blob/master/stdimage/management/commands/rendervariations.py#L43 by:

queryset = model_class._default_manager \

Select only correct field on querying model

Hi,

I'm using Django-stdimage and I changed the variations of one of my image field. I decided to run the rendervariations in a migration file.
It works perfectly, but then I added more migrations file for other changes. When I wanted to deploy it, my rendervariation migration script didn't work.
The other fields I added in the model didn't exist in the database yet because it was on further migration. I think if the query just select the required field, it would work.

Image quality automatically set to 75

When rendering all variations, image quality is changed to 75. Specifically Image.save(quality=75) is implied. There should be an optional argument for each variation that specifies quality.

South migration issue

I have last package from git and South don't want to do migaration.

ValueError: Cannot successfully create field 'photo' for model 'model1': name 'inf' is not defined.

There is issue in migration file, at db.alter_column

max_size={'width': inf, 'height': inf}

inf is not declared.

After I fix it I have new issue

ValueError: Cannot successfully create field 'photo' for model 'model1': 'list' object has no attribute 'iteritems'.

Admin widget refactoring

The admin widget needs refactoring. The field should store a smaller thumbnail to reduce IO and traffic.

add windows support please

windows can't rename file to exists file

add os.remove before all os.rename

if i try in windows replace image i got

Traceback:
 File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
 response = wrapped_callback(request, callback_args, *callback_kwargs) File "C:\Python27\lib\site-packages\django\contrib\admin\options.py" in wrapper
 return self.admin_site.admin_view(view)(args, *kwargs) File "C:\Python27\lib\site-packages\django\utils\decorators.py" in wrappedview
 response = view_func(request, args, *kwargs) File "C:\Python27\lib\site-packages\django\views\decorators\cache.py" in wrappedview_func
 response = view_func(request, args, *kwargs) File "C:\Python27\lib\site-packages\django\contrib\admin\sites.py" in inner
 return view(request, args, *kwargs) File "C:\Python27\lib\site-packages\django\utils\decorators.py" in _wrapper
 return bound_func(args, *kwargs) File "C:\Python27\lib\site-packages\django\utils\decorators.py" in wrappedview
 response = view_func(request, args, *kwargs) File "C:\Python27\lib\site-packages\django\utils\decorators.py" in bound_func
 return func(self, args2, *kwargs2) File "C:\Python27\lib\site-packages\django\db\transaction.py" in inner
 return func(args, *kwargs) File "C:\Python27\lib\site-packages\django\contrib\admin\options.py" in change_view
 self.save_model(request, new_object, form, True) File "C:\Python27\lib\site-packages\django\contrib\admin\options.py" in save_model
 obj.save() File "C:\Python27\lib\site-packages\django\db\models\base.py" in save
 force_update=force_update, update_fields=update_fields) File "C:\Python27\lib\site-packages\django\db\models\base.py" in save_base
 update_fields=update_fields, raw=raw, using=using) File "C:\Python27\lib\site-packages\django\dispatch\dispatcher.py" in send
 response = receiver(signal=self, sender=sender, **named) File "C:\Python27\lib\site-packages\stdimage\fields.py" in renameresize_image
 os.rename(filename, dst_fullpath)

Exception Type: WindowsError at /admin/x/banner/5/
 Exception Value: 183 file exists

Generate Progressive JPEG variation

Is there any possibility to create a progressive JPEG variation?

I mean, I see that it is not implemented yet. How hard would that be to add this functionality? Especially taking into account different image formats, like, say, generating a progressive JPEG variation of a PNG image.

Documentation on how to implement

Documentation states that "StdImageField works just like Django's own ImageField except that you can specify different sized variations.", but there is one huge difference, there is no widget. I've tried to make this work with a simple form and wasn't able to. Can you please supply a working example for the form template? Thanks!

UUID file names

Make optional scrambled filenames using UUID4 to protect against CURL hacks.

Problem with thumbnails after deployment

Hi,

on my local machine the following template snipet works perfectly fine:

<a href="{{ impression.image.url }}" class="gallery"><img src="{{ impression.image.large.url }}" border="0" /></a>

But after deployment to a remote apache_wsgi virtual host, thumbnails are nod beeing displayed. The main image, however, works fine.

Checking the URL of the thumbnails shows http://mydomain.com/media/images/imagesimage_1.large.jpeg
where the correct path was http://mydomain.com/media/images/image_1.large.jpeg.

Any idea what might cause this issue?

Simon

Unknown command: 'rendervariations

Hi, I'm trying to re-render the variantions using the rendervariations command from the readme but I get the following error:

Unknown command: 'rendervariations'
Type 'manage.py help' for usage.

Checking with python manage.py help doesn't show it in the available commands. What am I missing? Thanks!

South compatibility: has no attribute 'size'

After adding a new StdImageField in a class in my models.py, I tried to migrate with south causing the following error:

./manage.py schemamigration myapp --auto
AttributeError: 'StdImageField' object has no attribute 'size'

File size validator.

Hello!

I moved from humanfromearth's version to your and I have one question.

How I can change original image size? without variations.

I dont want to keep original size because sometimes clients upload real big images.

Exception NoSuchFile in rendervariations

Hello!
Please add force option if NoSuchFile exception.

./manage.py rendervariations app.model.image
IOError: [Errno 2] No such file or directory: u'/var/www/static/pic.gif'
and command stop now...

Rescale uploaded image before actual saving

Hi,
in order to save space on the hard drive I was looking how to get rid off unnecessary big original images.
As I understood it's not desirable behavior so I was hoping for a criticism of my workaround:
Gist

I'm not so good with python so might miss simpler way.

Anyway, love this project!

How can I use default variation?

I'd like to replace existing image field in my models with resized images by default. So without changing the rest of the code I would like to access myproduct.image.url to get url to already processed image instead of original one.

As I see from the code, default variation is not supported. Could you please add a variation named default to be returned by default instead of original one?

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.