jazzband / django-avatar Goto Github PK
View Code? Open in Web Editor NEWA Django app for handling user avatars.
License: BSD 3-Clause "New" or "Revised" License
A Django app for handling user avatars.
License: BSD 3-Clause "New" or "Revised" License
The last release, 1.0.5, happened on 2010-06-24, and it doesn't support django >=1.4.
It would be great if there was a proper release that supports newer django versions.
From pinax-user mailing list.
I’m using post_save signal to do stuff when a user changes his avatar.
After a user upload an avatar once, each time he log in I see that the post_save signal is firing and I don’t think it should.
To reproduce it you could just drop this code in one of your apps models.py
from django.db.models.signals import post_save
def change_avatar(sender, **kwargs):
print ‘post_save fired’
post_save.connect(change_avatar, sender=Avatar)
I can upload image successfully, but it doesn't create resized directory.I followed the document and I think my configuration of this app is correct(PIL is installed). Anyone has similar problem? how can I solve this problem
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/avatar/delete/
Django Version: 1.1
Python Version: 2.6.5
Installed Applications:
['django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
'django.contrib.webdesign',
'multilingual',
'multilingual.flatpages',
'news',
'news.templatetags',
'feedback',
'article',
'article.templatetags',
'institution',
'institution.templatetags',
'baner',
'baner.templatetags',
'threadedcomments',
'django.contrib.comments',
'rosetta',
'captcha',
'tools',
'tools.templatetags',
'accounts',
'avatar',
'debug_toolbar']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.middleware.locale.LocaleMiddleware',
'multilingual.middleware.DefaultLanguageMiddleware',
'multilingual.flatpages.middleware.FlatpageFallbackMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware')
Traceback:
File "/home/artem/prog/dev/anastasia_u4eba/env/lib/python2.6/site-packages/django/core/handlers/base.py" in get_response
response = callback(request, _callback_args, *_callback_kwargs)
return self.view_func(request, _args, *_kwargs)
notification.send([request.user], "avatar_updated", {"user": request.user, "avatar": a})
Exception Type: AttributeError at /avatar/delete/
Exception Value: 'NoneType' object has no attribute 'send'
In avatar/templatetags/avatar_tags.py:17 it seems that first wrapper applied is register.simple_tag, and only then cache_result; with that, rendering a template with many avatar_url tags is very slow since the cache is not used.
This might be problematic to fix mainly because of the default parameters; best thing that can be done of what I found is to use a separate function that's registered as a simple_tag, and calls original function (probably renamed), which is wrapped by the cache_result.
Just to say that I found a bug in a early version of this library, when you try to upload a picture that includes the symbol '#' in the file name. For example:
Photo on 2012-04-05 at 15.56 #3.jpg
These kind of file names are typical when using MacBook webcams.
So, I solved that using slugify() with the file name, in order to avoid strange characters. Something like:
# avatar/views.py
def add(...):
# ...
file_name = os.path.splitext(image_file.name)
name = file_name[0]
extension = file_name[1]
new_file_name = slugify(name) + extension
avatar.avatar.save(new_file_name, image_file)
# ...
There is a design flaw in this app as it supports 1> avatar per user. This makes it unnecessary hard to query users and avatars without N queries to the avatar table, where N is the number of Users you are retrieving. I suggest to simplify the app to only allow one avatar per user. If there were a OneToOne relationship between User..Avatar, we could do User.objects.select_related('avatar')
Noticed this when a user tried uploading an avatar with 'ä' in his avatar's filename.
Traceback (most recent call last):
File "/srv/styleloving/venv/lib/python2.6/site-packages/django/core/handlers/base.py", line 100, in get_response
response = callback(request, _callback_args, *_callback_kwargs)
File "/srv/styleloving/venv/lib/python2.6/site-packages/django/contrib/auth/decorators.py", line 25, in _wrapped_view
return view_func(request, _args, *_kwargs)
File "/srv/styleloving/venv/lib/python2.6/site-packages/avatar/views.py", line 63, in change
new_file = avatar.avatar.storage.save(path, request.FILES['avatar'])
File "/srv/styleloving/venv/lib/python2.6/site-packages/django/core/files/storage.py", line 47, in save
name = self.get_available_name(name)
File "/srv/styleloving/venv/lib/python2.6/site-packages/django/core/files/storage.py", line 73, in get_available_name
while self.exists(name):
File "/srv/styleloving/venv/lib/python2.6/site-packages/django/core/files/storage.py", line 196, in exists
return os.path.exists(self.path(name))
File "/usr/lib/python2.6/genericpath.py", line 18, in exists
st = os.stat(path)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe4' in position 53: ordinal not in range(128)
When using {% avatar_url user 30 %} and the user has no avatar, the no_avatar img shows in the default size.
Hello,
Uploading avatars works good but it doesn't create a resized folder nor resized images.
Any idea?
If AVATAR_HASH_USERDIRNAMES = False, directory-per-user will be created in AVATAR_STORAGE_DIR. When AVATAR_HASH_USERDIRNAMES = True it gets better, but is still directory-per-user after 2 levels of hash subdivision. At scale, this will get out of control. It seems like a strftime based folder structure (as encouraged by FileField) would keep nodes/directory at a manageable level.
Are there documentation on how to use the webcam upload feature?
Allowed letters in email http://en.wikipedia.org/wiki/Email#Content_encoding
The problems:
# File ".../python2.6/site-packages/avatar/templatetags/avatar_tags.py", line 36, in avatar_url
# md5_constructor(user.email).hexdigest(),
#
#UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-3: ordinal not in range(128)
Solution:
return "http://www.gravatar.com/avatar/%s/?%s" % (
- md5_constructor(user.email).hexdigest(),
+ md5_constructor(user.email.encode("utf-8")).hexdigest(),
urllib.urlencode(params))
If, for whatever reason, the file for someone's avatar doesn't exist, the page 500s. It would be much better if the error was caught and the user just got a broken image rather than the entire page being unusable simply because of a broken avatar.
Right now, it seems that the user can upload as many avatars as they wish. How do I restrict it so that she can only have 3 avatars?
I was thinking of AVATAR_MAX_AVATARS_PER_USER?
Do I put this in settings.py?
I just received this error when uploading a new avatar:
AttributeError at /avatar/change/
'User' object has no attribute 'message_set'
Request Method: POST
Request URL: http://127.0.0.1:8000/avatar/change/
Django Version: 1.5.2
Exception Type: AttributeError
Exception Value:
'User' object has no attribute 'message_set'
Exception Location: /Library/Python/2.7/site-packages/django/utils/functional.py in inner, line 205
I think there is a problem with support of django 1.5.X
Can you fix this asap? 👍
Version: 1.0.5 pip install
Need to restrict file type to just image files. Right now, django-avatar is allowing any time of file to be uploaded.
I tried installing the zipball version on here which is 1.0.3, however, it does not allow anything to be uploaded
Please move from Google Code to Github :)
The hashcompat used by django-gravatar and django-avatar has been marked as deprecated and is scheduled for removal in Django 1.6. From what I can tell, the desired alternative is to use the built-in hashlib module instead.
I submitted a pull request to django-gravatar to fix this: https://github.com/nvie/django-gravatar/pull/4
The problem is I can upload any kind of a file without getting a validation error. In fact this is rather usability bug not related with the pure code.
I was able to upload .exe and .xls files and found them in users image directory, is that correct?
I didn't look at the code.
Hi, we'd like to have this app support class based views, so that it would be easy to change a templating engine. (we have a forked version supporting jinja2 along with a set of jinja2 templates)
Would this ever have a chance to be included into the "trunk" version?
Thanks.
Evgeny.
Is there a way to attach avatars to other things than Users? I'd like to use it to attach avatars (well, company logos) to my Company objects (and I really like the mgmt stuff you bring.)
I'm displaying a page with around 60 avatars and django is making a query for each one of them. I cannot use User.objects.select_related('avatar')
because there is no link between my user and his avatar. So how do I optimize this?
Hey,
the official package seems to be hopelessly outdated, and it seems that most of the development has happened in your tree You should take over maintenance and release a package to pypi.
When resizing an image that is not of jpeg type (e.g. png or gif), the resulting image is converted into jpeg, but the extension is maintained from the original. The resulting image can't be opened as the extension does not match the real image type anymore.
avatar_img(avatar, size) doesnt check unicode(avatar) and the variable avatar is built according to user data. When user name is sufficiently weird, any HTML can be injected.
The delete function should have the login_required decorator. There is a bug in the last line of views.py: a duplicate line change = login_required(change) instead of delete = login_required(delete)
Hi,
We have a medium-sized Django site that uses django-avatar for profile pictures.
Our admins need to be able to upload avatars on behalf of other users.
If we send you a pull request implementing this functionality, would you be open to accepting it?
Hi,
Thanks for this awesome Django app. Works like a charm. However, I'd like to suggest one little change to models.Avatar.avatar_url()
settings.MEDIA_URL is the usual parameter to point to static files in Django projects as you will know.
Thus, serving avatar pix stored on local f/s space should return as the avatar_url MEDIA_URL + '/avatars'
IOW,
diff --git a/avatar/models.py b/avatar/models.py
index 4875776..f0b7bb3 100644
--- a/avatar/models.py
+++ b/avatar/models.py
@@ -2,6 +2,7 @@ import datetime
import os.path
from django.db import models
+from django.conf import settings
from django.core.files.base import ContentFile
from django.utils.translation import ugettext as _
from django.utils.hashcompat import md5_constructor
@@ -110,7 +111,8 @@ class Avatar(models.Model):
thumb = self.avatar.storage.save(self.avatar_name(size), thumb_file)
def avatar_url(self, size):
- return self.avatar.storage.url(self.avatar_name(size))
+ return settings.MEDIA_URL.rstrip('/') + self.avatar.storage.url(
+ self.avatar_name(size))
def avatar_name(self, size):
ext = find_extension(AVATAR_THUMB_FORMAT)
or the like...
Thanks,
Frank
(models.py - lines 102-104 in create_thumbnail)
image = image.resize((size, size), AVATAR_RESIZE_METHOD)
if image.mode != "RGB":
image = image.convert("RGB")
should actually be
if image.mode != "RGB":
image = image.convert("RGB")
image = image.resize((size, size), AVATAR_RESIZE_METHOD)
"Any resizing done in the original limited palette mode is likely to produce jaggy rubbish because of the lack of available in-between colours in the palette; and ANTIALIAS is the only resize filter that is intended to be used for downscaling: BILINEAR and BICUBIC really do only take two pixels per axis and blend between them, which is fine for upscaling but doesn't work at all when one or both axes are downscaled." - bobince
When the below code is run (which results if you pass in a user that doesn't exist... I put User ID instead of username in the render_primary view) it will return a "default url" which is a string. The view then tries to use the result as if it was an avatar object and it ... explodes.
def get_primary_avatar(user, size=80):
if not isinstance(user, User):
try:
user = User.objects.get(username=user)
except User.DoesNotExist:
return get_default_avatar_url() # <~~~ inappropriate return type.
I am trying to download the 2.0a1 tarball as part of a django setup.py build and test automated process. Most of the django-avatar tests are failing because the testdata folder is missing.
Otherwise, if I install django-avatar with git clone, there is no problem and the tests are all ok.
Hi,
im using png with trasparency as avatars, but i've some problem creating thumbs due to
if image.mode != "RGB":
image = image.convert("RGB")
I already added to my settings:
AVATAR_THUMB_FORMAT = 'png'
I would preserve the image.mode when it's RGBA.
Do you have any idea? I guess it could be enough skip the conversion step.
README does not state how to run tests (in order to submit patches). This is not probably what is needed:
python setup.py test
running test
If AVATAR_HASH_FILENAMES = False, a thumbnail retains the original file's extension no matter what the value of AVATAR_THUMB_FORMAT is. For instance, if I upload foo.png but AVATAR_THUMB_FORMAT = 'JPEG', my thumbnail will be a JPEG called foo.png.
models.avatar_file_path should use the extension it's given no matter the value of AVATAR_HASH_FILENAMES. This means that it is also required to avoid filename collisions just as Django's FileField does.
If you use the avatar template tag, django-avatar will fall back to gravatar if it's configured. However, when the view render_primary() is used, there is no gravatar fallback.
I didn't really find this clearly documented anywhere and I found the behavior inconsistent.
I've created a Danish locale file for django-avatar. Please include it in the project... since there doesn't seem to be an attachment option here, you can get it from:
http://daimi.au.dk/~illio/pinax/django-avatar/django.po
It's in UTF-8.
When django-avatars is installed in the Python 2.7/django 1.6.5 environment and the module added to the installed apps, the import fails with the message:
Line: 11 - from django.utils import six
ImportError: cannot import name six
Is there a workaround for this? Have they moved six? Is there an earlier version I can install of django-avatars to avoid this issue?
Hello, we fixed this issue in askbot - each user has a denormalized record on whether they have a real avatar or not.
Actually - the record stores type of avatar: auto-gravatar, uploaded gravatar, locally uploaded avatar.
Would you like to include this into django-avatar? Probably most of the code can be borrowed from askbot, we could help too.
This record helps to avoid displaying auto-generated gravatars, which look quite ugly especially if you show a few side by side.
e.g:
I had three sizes, (30,30), (50,50), (80,80), update cache just delete specific avatar size, In the nav, it called {% avatar 30 %}, and invalidate_cache just deleted (30,30) avatar, and (50,50), (80,80) would not deleted.
May be can specific all sizes configuration, e.g ALL_SIZES, in setting, and
invalidate_cache looking for ALLEN_SIZES, and delete all sizes of avatar in cache backend.
Should instead suppress messages like "Rebuilding Avatar id=52 at size 160."
I get the following error when running manage.py with 'avatar' in my INSTALLED_APPS
ImportError: No module named Image
I installed pillow and got it working. I think you can add something like the following to setup.py to make it install pillow (I think you can use PIL instead if you chose.) automatically when using pip.
install_requires=[
"pillow",
],
pip freeze
Django==1.5
django-avatar==1.0.5
Pillow==2.0.0
Thanks for all the good work, it works like a charm.
I'm getting this error when I go to http://127.0.0.1:8000/avatar/change/
and click the button 'Upload New Image':
Forbidden (403) CSRF verification failed. Request aborted.
So I went to python27/Lib/site-packages/avatar/templates/avatar/change.html
and added
{% csrf_token %}
right after <form ... POST...>
.
When I refresh the browser and view source I do not see the CSRF token, and the 403 message is still generated.
How do I modify the 'correct' django-avatar template?
I'm seeing the built in template tags always point to MEDIA_URL. Can we define a static location to point to like http://www.testing.com/newDirectory/avatar/user/65/image.png?
Many a times like with fb authentication / twitter auth we can get link to profile image from the provider. In such cases can we avoid storing image and instead just store the link to the image ?
Hello,
(Please let me know if I need to follow a different protocol for submitting this piece of information. It's my first time submitting anything to an open source project.)
if AVATAR_GRAVATAR_BACKUP:
# didn't work:
#return "http://www.gravatar.com/avatar/%s/?%s" % (
# works (note the slash before the ? is removed):
return "http://www.gravatar.com/avatar/%s?%s" % (
hashlib.md5(user.email).hexdigest(),
urllib.urlencode({'s': str(size)}),)
)
When defaulting to a Gravatar, my application was not finding the actual Gravatar but was instead always returning the default blue Gravatar "G". I compared the link text in the code with the link format spec on Gravatar.com and found that there was an extra slash at the end of the link. I removed this on my install, and now it works.
Thanks.
When I'm trying delete user (who has some avatars) from admin panel, I get an error:
DoesNotExist at /admin/auth/user/
User matching query does not exist. Lookup parameters were {u'id__exact': 11}
Exception Location: /usr/local/lib/python2.7/dist-packages/django/db/models/query.py in get, line 389
/home/testDjango/frontend/avatar/models.py in invalidate_avatar_cache
invalidate_cache(instance.user) ...
▼Local vars
Variable Value
instance
<Avatar: Avatar for test>
sender
<class 'avatar.models.Avatar'>
kwargs
{'signal': <django.dispatch.dispatcher.Signal object at 0x250c050>,
'using': 'default'}
In Django 1.4, your messaging system doesnt work. Because the messaging system of django has been changed in 1.4.
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.