Beispiel #1
0
    def render(self, context):
        # If size is not an int, then it's a Variable, so try to resolve it.
        size = self.size
        if not isinstance(size, int):
            size = int(self.size.resolve(context))

        if not size in AVATAR_SIZES:
            return ''

        try:
            user = self.user.resolve(context)
            if DEFAULT_AVATAR_FOR_INACTIVES_USER and not user.is_active:
                raise
            avatar = Avatar.objects.get(user=user, valid=True).image
            if hasattr(settings, "AWS_SECRET_ACCESS_KEY"):
                avatar_path = avatar.name
            else:
                avatar_path = avatar.path

            if not storage.exists(avatar_path):
                raise
            base, filename = os.path.split(avatar_path)
            name, extension = os.path.splitext(filename)
            filename = os.path.join(base, "%s.%s%s" % (name, size, extension))
            base_url = avatar.url
            url = os.path.join(base, "%s.%s%s" % (name, self.size, extension))

        except:
            avatar_path = DEFAULT_AVATAR
            avatar = open(avatar_path)
            base, filename = os.path.split(avatar_path)
            name, extension = os.path.splitext(filename)
            filename = os.path.join(base, "%s.%s%s" % (name, size, extension))
            base_url = filename.replace(settings.MEDIA_ROOT, settings.MEDIA_URL)

        url_tuple = urlparse.urlparse(base_url)
        url = urlparse.urljoin(urllib.unquote(urlparse.urlunparse(url_tuple)), "%s.%s%s" % (name, size, extension))

        if not storage.exists(filename):
            thumb = Image.open(ContentFile(avatar.read()))
            img_format = thumb.format
            if not getattr(settings, 'CAN_ENLARGE_AVATAR', True ) or (thumb.size[0] > size or thumb.size[1] > size or not hasattr(thumb, 'resize')):
                thumb.thumbnail((size, size), Image.ANTIALIAS)
            else:
                thumb = thumb.resize((size, size), Image.BICUBIC)
            f = StringIO()
            try:
                thumb.save(f, img_format, **SAVE_IMG_PARAMS.get(img_format, {}))
            except:
                thumb.save(f, img_format)
            f.seek(0)
            storage.save(filename, ContentFile(f.read()))

        return url
Beispiel #2
0
def avatarchoose(request):
    """
    Avatar choose
    """
    profile, created = Profile.objects.get_or_create(user = request.user)
    images = dict()

    if hasattr(settings, "AVATAR_QUOTA"):
        request.upload_handlers.insert(0, QuotaUploadHandler())

    if request.method == "POST":
        form = AvatarForm()
        if request.POST.get('keyword'):
            keyword = iri_to_uri(request.POST.get('keyword'))
            gd_client = gdata.photos.service.PhotosService()
            feed = gd_client.SearchCommunityPhotos(query = "%s&thumbsize=72c" % keyword.split(" ")[0], limit='48')
            for entry in feed.entry:
                images[entry.media.thumbnail[0].url] = entry.content.src

        else:
            form = AvatarForm(request.POST, request.FILES)
            if form.is_valid():
                image = form.cleaned_data.get('url') or form.cleaned_data.get('photo')
                try:
                    thumb = Image.open(ContentFile(image.read()))
                except:
                    messages.error(request, _("This image can't be used as an avatar"))
                else:
                    thumb.thumbnail((480, 480), Image.ANTIALIAS)
                    f = StringIO()
                    save_img_params = SAVE_IMG_PARAMS.get(thumb.format, {})
                    try:
                        thumb.save(f, thumb.format, **SAVE_IMG_PARAMS.get(thumb.format, {}))
                    except:
                        thumb.save(f, thumb.format)
                    f.seek(0)
                    avatar = Avatar(user=request.user, image="", valid=False)
                    file_ext = image.content_type.split("/")[1] # "image/gif" => "gif"
                    if file_ext == 'pjpeg':
                        file_ext = 'jpeg'
                    avatar.image.save("%s.%s" % (request.user.username, file_ext), ContentFile(f.read()))
                    avatar.save()

                    signal_responses = signals.post_signal.send(sender=avatarchoose, request=request, form=form)
                    return signals.last_response(signal_responses) or HttpResponseRedirect(reverse("profile_avatar_crop"))

    else:
        form = AvatarForm()

    if DEFAULT_AVATAR:
        base, filename = os.path.split(DEFAULT_AVATAR)
        filename, extension = os.path.splitext(filename)
        generic = "%s/%s.%d%s" % (base, filename, DEFAULT_AVATAR_SIZE, extension)
        generic = generic.replace(settings.MEDIA_ROOT, settings.MEDIA_URL)
    else:
        generic = ""

    template = "member/avatar/choose.html"
    data = { 'generic': generic, 'form': form, "images": images,
             'AVATAR_WEBSEARCH': AVATAR_WEBSEARCH, 'section': 'avatar',
             'DEFAULT_AVATAR_SIZE': DEFAULT_AVATAR_SIZE, 'MIN_AVATAR_SIZE': MIN_AVATAR_SIZE }
    signals.context_signal.send(sender=avatarchoose, request=request, context=data)
    return render_to_response(template, data, context_instance=RequestContext(request))
Beispiel #3
0
def avatarchoose(request):
    """
    Avatar choose
    """
    profile, created = Profile.objects.get_or_create(user=request.user)
    images = dict()

    if hasattr(settings, "AVATAR_QUOTA"):
        request.upload_handlers.insert(0, QuotaUploadHandler())

    if request.method == "POST":
        form = AvatarForm()
        if request.POST.get('keyword'):
            keyword = iri_to_uri(request.POST.get('keyword'))
            gd_client = gdata.photos.service.PhotosService()
            feed = gd_client.SearchCommunityPhotos(query="%s&thumbsize=72c" %
                                                   keyword.split(" ")[0],
                                                   limit='48')
            for entry in feed.entry:
                images[entry.media.thumbnail[0].url] = entry.content.src

        else:
            form = AvatarForm(request.POST, request.FILES)
            if form.is_valid():
                image = form.cleaned_data.get('url') or form.cleaned_data.get(
                    'photo')
                try:
                    thumb = Image.open(ContentFile(image.read()))
                except:
                    messages.error(request,
                                   _("This image can't be used as an avatar"))
                else:
                    thumb.thumbnail((480, 480), Image.ANTIALIAS)
                    f = StringIO()
                    save_img_params = SAVE_IMG_PARAMS.get(thumb.format, {})
                    try:
                        thumb.save(f, thumb.format,
                                   **SAVE_IMG_PARAMS.get(thumb.format, {}))
                    except:
                        thumb.save(f, thumb.format)
                    f.seek(0)
                    avatar = Avatar(user=request.user, image="", valid=False)
                    file_ext = image.content_type.split("/")[
                        1]  # "image/gif" => "gif"
                    if file_ext == 'pjpeg':
                        file_ext = 'jpeg'
                    avatar.image.save(
                        "%s.%s" % (request.user.username, file_ext),
                        ContentFile(f.read()))
                    avatar.save()

                    signal_responses = signals.post_signal.send(
                        sender=avatarchoose, request=request, form=form)
                    return signals.last_response(
                        signal_responses) or HttpResponseRedirect(
                            reverse("profile_avatar_crop"))

    else:
        form = AvatarForm()

    if DEFAULT_AVATAR:
        base, filename = os.path.split(DEFAULT_AVATAR)
        filename, extension = os.path.splitext(filename)
        generic = "%s/%s.%d%s" % (base, filename, DEFAULT_AVATAR_SIZE,
                                  extension)
        generic = generic.replace(settings.MEDIA_ROOT, settings.MEDIA_URL)
    else:
        generic = ""

    template = "member/avatar/choose.html"
    data = {
        'generic': generic,
        'form': form,
        "images": images,
        'AVATAR_WEBSEARCH': AVATAR_WEBSEARCH,
        'section': 'avatar',
        'DEFAULT_AVATAR_SIZE': DEFAULT_AVATAR_SIZE,
        'MIN_AVATAR_SIZE': MIN_AVATAR_SIZE
    }
    signals.context_signal.send(sender=avatarchoose,
                                request=request,
                                context=data)
    return render_to_response(template,
                              data,
                              context_instance=RequestContext(request))