codingjoe / django-stdimage Goto Github PK
View Code? Open in Web Editor NEWThis project forked from xarg/django-stdimage
Django Standardized Image Field
License: MIT License
This project forked from xarg/django-stdimage
Django Standardized Image Field
License: MIT License
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...
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?
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?
A 4th attribute for each variation to specify the quality.
Using the tuple system does work: variations={'thumbnail': (100, 75)})
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!
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
Hello!
Some mistakes in documentation at following string
`
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
.
The locale does not get picked up during the packaging processes, nether are they compiled.
When deleting an image the files are deleted correctly, but the database is not being updated.
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?
There have been changes in the recent implementation of management commands in django 1.8.
The current command should be updated.
Thanks @arbiterr for reporting.
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!
CodeRef:
https://github.com/codingjoe/django-stdimage/blob/master/stdimage/models.py#L39-L40
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'
in file rendervariations.py have in line 4 #import resource but don't find.
Make optional scrambled filenames using UUID4 to protect against CURL hacks.
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.
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)
The admin widget needs refactoring. The field should store a smaller thumbnail to reduce IO and traffic.
Getting rid of all filesystem code and replace it with django-storage api.
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.
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
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.
If the StdImageField is edited (new file uploaded) then old file should automatically be removed from filesystem.
This could be made optional also in case someone wants to clean filesystem themselves
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.
How can i achieve such file names like [email protected] (for original), [email protected] (variation), filename.jpeg (variation). By default original image has no postfix and i want to add it.
Thanks
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?
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!
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.
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.
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! ๐ค
Add travis-ci testing to ensure better builds.
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.
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.
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.
Create variations on the fly, when you update your field variations.
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'
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">
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!
See title.
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:
python manage.py rendervariations 'app_name.model_name.field_name' --replace
render_variation
from StdImageFieldFile
not with function from 1.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
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
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'.
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.
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 \
When stdimage creates variations, exif data is removed. Some devices (iOS) don't rotate an image, they only write EXIF orientation data. So after variations are created, it's impossible to set the correct orientation
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.