Code Monkey home page Code Monkey logo

django-stdimage's Issues

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

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?

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?

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!

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

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.

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?

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!

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'

UUID file names

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

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

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)

Admin widget refactoring

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

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.

`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

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.

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.

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?

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!

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.

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

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! ๐Ÿค–

Travis-CI

Add travis-ci testing to ensure better builds.

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.

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.

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.

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'

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!

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.

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

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

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

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.

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 \

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.