示例#1
0
    def get_thumbnail(self, obj):

        if obj.cropped_image:
            #return obj.cropped_image.url
            return thumbnail_url(obj.cropped_image, 'cropped')
        else:
            #return obj.image.url
            return thumbnail_url(obj.image, 'uncropped')
示例#2
0
 def get_image_url(self, obj):
     try:
         if obj.image != None:
             return thumbnail_url(obj.image, 'explore_box')
         else:
             return thumbnail_url(
                 obj.most_popular_recipe_cover_image.image_url,
                 'recipe_step')
     except:
         return settings.STATIC_URL + 'img/chef_cover.jpg'
示例#3
0
def memorial_view(request, memorial_slug):
    memorial_data = get_object_or_404(Memorial.objects.select_related(), slug=memorial_slug)

    catalog_image = memorial_data.catalog_image()

    data_to_render = {
        'pk': memorial_data.pk,
        'ordered_images': [],
        'catalog_image': thumbnail_url(catalog_image.photo, 'product') if catalog_image else False,
        'title': memorial_data.title,
        'description': memorial_data.description,
        'seo_description': memorial_data.seo_description,
        'seo_keywords': memorial_data.seo_keywords,
        'base_price': memorial_data.base_price,
        'formatted_price': memorial_data.formatted_price()
    }

    ordered_images = memorial_data.ordered_images()
    # getting thumbs just suck much
    # slow as hell
    for image in ordered_images:
        data_to_render['ordered_images'].append({
            'product': thumbnail_url(image.photo, 'product'),
            'preview': thumbnail_url(image.photo, 'preview')
        })

    stella_variants = []
    for stella in memorial_data.stella_variants.prefetch_related('cvetnik', 'polirovka', 'podstavka').all():
        stella_variants.append({
            'added_value': stella.added_value,
            'pk': stella.pk,
            'title': stella.title,
            'lightbox_info': stella.lightbox_info,
            'length': stella.length,
            'width': stella.width,
            'height': stella.height,
            'data_size': stella.data_size,
            'text_size': stella.text_size,

            'cvetnik_set': stella.cvetnik.all(),
            'polirovka_set': stella.polirovka.all(),
            'podstavka_set': stella.podstavka.all(),
        })

    # add 1 to popularity of this particular monument on view
    memorial_data.popularity += 1

    # memorial_data.save()
    threading.Thread(target=memorial_data.save).start()

    return render(request, 'product.html', {
        'memorial': data_to_render,
        'stella_variants': stella_variants
    })
示例#4
0
 def cover_thumb(self, type):
     try:
         if self.cover:
             thumb = thumbnail_url(self.cover, type)
             return thumb
         else:
             best_recipe = self.best_recipe
             if best_recipe:
                 thumb = thumbnail_url(best_recipe.cover, type)
                 return thumb
             else:
                 return settings.STATIC_URL + 'img/chef_cover.jpg'
     except Exception, e:
         return settings.STATIC_URL + 'img/chef_cover.jpg'
示例#5
0
    def get_context(self, name, value, attrs):
        context = super().get_context(name, value, attrs)

        img_url = None
        value = context['widget']['value']
        if value:
            img_url = thumbnail_url(value, self.thumbnail_size)

        if not img_url:
            img_url = self.placeholder

        context['widget'].update({
            'img_url':
            img_url,
            'img_size':
            self.img_size,
            'img_type':
            self.img_type,
            'img_extra_class':
            self.img_extra_class,
            'is_initial':
            self.is_initial(self.initial_text),
            'placeholder':
            self.placeholder,
        })
        return context
示例#6
0
    def to_representation(self, instance):

        if not instance:
            return

        return '{}{}'.format(SITE_URL, thumbnail_url(instance,
                                                     'thumbnail_240'))
示例#7
0
    def post(self, request, chef_id):
        try:
            chef = Chefs.objects.get(id=chef_id)

            if chef != request.user:
                return Response({
                    'success': False,
                },
                                status=status.HTTP_403_FORBIDDEN)

            restaurant, created = Restaurant.objects.get_or_create(chef=chef)
            restaurant.image = request.FILES['image']
            restaurant.save()

            cache = get_cache('default')
            restaurant_image_key = CacheUtils.get_key(
                CacheUtils.CHEF_RESTAURANT_IMAGE, chef_id=chef_id)
            restaurant_image = thumbnail_url(restaurant.image,
                                             'library_restaurant_cover')
            cache.set(restaurant_image_key, restaurant_image)

            return Response({
                'success': True,
                'url': restaurant.thumb_account_button
            })

        except Exception, e:
            return Response({
                'success': False,
                'error': e
            },
                            status=status.HTTP_400_BAD_REQUEST)
示例#8
0
def profile_pic(user):
    output = ""
    if user.google_pic:
        output = '<img src="%s" class="user-pic">' % thumbnail_url(user.google_pic, "thumb")
    else:
        output = '<img src="%s" class="user-pic missing">' % staticfiles_storage.url("app/img/missing_pic.gif")
    return output
def download_image(potd, redownload=False):
    """Downloads the image to the corresponding potd, returns True if image (re-)downloaded"""
    if potd.image and not redownload:
        logger.info('skipping re-downloading of image for {}'.format(potd))
        return False
    if not potd.image_url and not potd.image_thumbnail_url:
        logger.warning('no image URL for {}'.format(potd))
        return False
    if not potd.pk:
        potd.save()
    try:
        # TODO: figure out why thumbnails don't get deleted this way
        thumbnailer = get_thumbnailer(potd.image)
        thumbnails_deleted = thumbnailer.delete_thumbnails()
        logger.debug('extractor image download: deleted {} thumbnails'.format(
            thumbnails_deleted))

        # prefer the smaller thumbnail url if available
        image_url = potd.image_thumbnail_url or potd.image_url
        image_response = requests.get(image_url)
        potd.image.delete(False)
        potd.image.save(
            os.path.split(potd.image_url)[1],
            ContentFile(image_response.content))
        # pre-create thumbnails by getting the url
        for thumb_type in settings.THUMBNAIL_ALIASES_TO_PREGENERATE:
            logger.debug('extractor image download: thumb [{}]: {}'.format(
                thumb_type, thumbnail.thumbnail_url(potd.image, thumb_type)))
        return True
    except Exception as e:
        logger.error('extractor image download failure: {}'.format(e))
        return False
示例#10
0
文件: views.py 项目: interlegis/sigi
def parliament_summary(parliament):
    summary = {
        'nome': parliament.nome + ', ' + parliament.municipio.uf.sigla,
        'thumb': thumbnail_url(parliament.foto, 'small'),
        'foto': (parliament.foto.url if parliament.foto else ''),
        'lat': str(parliament.municipio.latitude),
        'lng': str(parliament.municipio.longitude),
        'estado': parliament.municipio.uf.sigla,
        'regiao': parliament.municipio.uf.regiao,
        'gerente': (str(parliament.gerente_contas.id) if parliament.gerente_contas else ''),
        'diagnosticos': [],
        'seit': [],
        'convenios': [],
        'equipadas': [],
        'info': []
    }
    
    if parliament.gerente_contas:
        summary['info'].append(_(u"Gerente de relacionamento: %s") % parliament.gerente_contas.nome_completo)

    for sv in parliament.servico_set.filter(data_desativacao=None):
        summary['info'].append(
            _(u"%(name)s ativado em %(date)s") % dict(
                name=sv.tipo_servico.nome,
                date=sv.data_ativacao.strftime('%d/%m/%Y') if sv.data_ativacao else _(u'<sem data de ativação>')) +
            " <a href='%s' target='_blank'><img src='%simg/link.gif' alt='link'></a>" % (sv.url, STATIC_URL))
        summary['seit'].append(sv.tipo_servico.sigla)

    for cv in parliament.convenio_set.all():
        if (cv.data_retorno_assinatura is None) and (cv.equipada and cv.data_termo_aceite is not None):
            summary['info'].append(_(u"Equipada em %(date)s pelo %(project)s") % dict(
                date=cv.data_termo_aceite.strftime('%d/%m/%Y'),
                project=cv.projeto.sigla))
            summary['equipadas'].append(cv.projeto.sigla)
        elif cv.data_retorno_assinatura is None:
            summary['info'].append(_(u"Adesão ao projeto %(project)s, em %(date)s") % dict(
                project=cv.projeto.sigla,
                date=cv.data_adesao))
            summary['convenios'].append(cv.projeto.sigla)
        if (cv.data_retorno_assinatura is not None) and not (cv.equipada and cv.data_termo_aceite is not None):
            summary['info'].append(_(u"Conveniada ao %(project)s em %(date)s") % dict(
                project=cv.projeto.sigla,
                date=cv.data_retorno_assinatura.strftime('%d/%m/%Y')))
            summary['convenios'].append(cv.projeto.sigla)
        if (cv.data_retorno_assinatura is not None) and (cv.equipada and cv.data_termo_aceite is not None):
            summary['info'].append(_(u"Conveniada ao %(project)s em %(date)s e equipada em %(equipped_date)s") % dict(
                project=cv.projeto.sigla,
                date=cv.data_retorno_assinatura.strftime('%d/%m/%Y'),
                equipped_date=cv.data_termo_aceite.strftime('%d/%m/%Y')))
            summary['equipadas'].append(cv.projeto.sigla)
            summary['convenios'].append(cv.projeto.sigla)

    for dg in parliament.diagnostico_set.all():
        summary['diagnosticos'].append('P' if dg.publicado else 'A')
        summary['info'].append(_(u'Diagnosticada no período de %(initial_date)s a %(final_date)s') % dict(
            initial_date=dg.data_visita_inicio.strftime('%d/%m/%Y') if dg.data_visita_inicio is not None else _(u"<sem data de início>"),
            final_date=dg.data_visita_fim.strftime('%d/%m/%Y') if dg.data_visita_fim else _(u"<sem data de término>")))

    return summary
示例#11
0
 def thumbnail(self):
     """
         Picture thumbnail url
     """
     if self.picture:
         return thumbnail_url(self.picture, 'feed_image')
     else:
         return None
示例#12
0
 def get_chef_thumb(self, obj):
     try:
         thumb = thumbnail_url(obj.avatar, 'chef_avatar')
         if thumb:
             return thumb
         else:
             return settings.STATIC_URL + 'img/chef_avatar.jpg'
     except:
         return ''
示例#13
0
 def thumb(self, type):
     try:
         if self.cover:
             thumb = thumbnail_url(self.cover, type)
             return thumb
         else:
             return settings.STATIC_URL + 'img/chef_cover.jpg'
     except Exception, e:
         return settings.STATIC_URL + 'img/chef_cover.jpg'
示例#14
0
def thumb(source, alias):
    """
    This filter modifies that from `easy_thumbnails` so that
    it can neglect .svg file.
    """
    if source.url.endswith('.svg'):
        return source.url
    else:
        return thumbnail_url(source, alias)
示例#15
0
 def thumb_account_button(self):
     try:
         if self.image:
             thumb = thumbnail_url(self.image, 'account_button')
             return thumb
         else:
             return settings.STATIC_URL + 'img/restaurant_cover.png'
     except Exception, e:
         return settings.STATIC_URL + 'img/restaurant_cover.png'
示例#16
0
 def avatar_thumb(self, type):
     try:
         if self.avatar:
             thumb = thumbnail_url(self.avatar, type)
             return thumb
         else:
             return settings.STATIC_URL + 'img/chef_avatar.jpg'
     except Exception, e:
         return settings.STATIC_URL + 'img/chef_avatar.jpg'
示例#17
0
    def to_representation(self, value):
        if not value:
            return None

        url = thumbnail_url(value, self.alias)
        request = self.context.get('request', None)
        if request is not None:
            return request.build_absolute_uri(url)
        return url
示例#18
0
 def thumb_global_search(self, obj):
     try:
         if obj.cover:
             thumb = thumbnail_url(obj.cover, 'global_search')
             return thumb
         else:
             return settings.STATIC_URL + 'img/chef_cover.jpg'
     except Exception, e:
         return settings.STATIC_URL + 'img/chef_cover.jpg'
示例#19
0
 def thumb_chefs_box(self):
     try:
         if self.cover:
             thumb = thumbnail_url(self.cover, 'chefs_box')
             return thumb
         else:
             return settings.STATIC_URL + 'img/chef_cover.jpg'
     except Exception, e:
         return settings.STATIC_URL + 'img/chef_cover.jpg'
示例#20
0
 def thumb_chefs_nav_avatar(self):
     try:
         if self.avatar:
             thumb = thumbnail_url(self.avatar, 'base_nav_avatar')
             return thumb
         else:
             return settings.STATIC_URL + 'img/chef_avatar.jpg'
     except Exception, e:
         return settings.STATIC_URL + 'img/chef_avatar.jpg'
示例#21
0
    def post(self, request, chef_id):
        try:
            chef = Chefs.objects.get(id=chef_id)

            if chef != request.user:
                return Response({'success': False},
                                status=status.HTTP_403_FORBIDDEN)

            photo, created = Photos.objects.get_or_create(chef=chef)

            photo.image_url = request.FILES['image']
            photo.save()

            photo.s3_url = photo.image_url.url  # Ensure same value as image_url
            photo.save()

            cache = get_cache('default')
            chef_avatar_key = CacheUtils.get_key(CacheUtils.CHEF_AVATAR,
                                                 chef_id=chef_id)
            chef_avatar = thumbnail_url(chef.avatar, 'chef_avatar')
            cache.set(chef_avatar_key, chef_avatar)

            chef_base_avatar_key = CacheUtils.get_key(
                CacheUtils.CHEF_BASE_NAV_AVATAR, chef_id=chef_id)
            chef_base_avatar = thumbnail_url(chef.avatar, 'base_nav_avatar')
            cache.set(chef_base_avatar_key, chef_base_avatar)

            if chef == request.user:
                avatar_key = CacheUtils.get_key(CacheUtils.USER_AVATAR,
                                                user_id=chef_id)
                avatar = thumbnail_url(photo.image_url, 'base_nav_avatar')
                cache.set(avatar_key, avatar)

            return Response({
                'success': True,
                'url': chef.avatar_thumb('chef_avatar')
            })

        except Exception, e:
            return Response({
                'success': False,
                'error': e
            },
                            status=status.HTTP_400_BAD_REQUEST)
示例#22
0
    def to_representation(self, instance):

        if not instance:
            return None

        url = thumbnail_url(instance, 'thumbnail_240')
        if not url:
            return None

        return '{}{}'.format(SITE_URL, url)
示例#23
0
def user_avatar(request):
    avatar = None
    if request.user.is_authenticated():
        cache = get_cache('default')
        key = CacheUtils.get_key(CacheUtils.USER_AVATAR,
                                 user_id=request.user.id)
        avatar = cache.get(key, None)
        if avatar is None:
            avatar = thumbnail_url(request.user.avatar, 'base_nav_avatar')
            cache.set(key, avatar)
    return {'USER_AVATAR': avatar}
示例#24
0
    def post(self, request, chef_id):
        try:
            chef = Chefs.objects.get(id=chef_id)

            if chef != request.user:
                return Response({
                    'success': False,
                },
                                status=status.HTTP_403_FORBIDDEN)

            chef.cover = request.FILES['image']
            chef.save()

            cache = get_cache('default')
            chef_cover_key = CacheUtils.get_key(CacheUtils.CHEF_COVER,
                                                chef_id=chef_id)
            chef_cover = thumbnail_url(chef.cover, 'library_cover')
            cache.set(chef_cover_key, chef_cover)

            chef_edit_cover_key = CacheUtils.get_key(
                CacheUtils.CHEF_EDIT_COVER, chef_id=chef_id)
            chef_edit_cover = thumbnail_url(chef.cover,
                                            'library_edit_modal_cover')
            cache.set(chef_edit_cover_key, chef_edit_cover)

            chef_key = CacheUtils.get_key(CacheUtils.CHEF, chef_id=chef_id)
            cache.set(chef_key, chef)

            return Response({
                'success': True,
                'url': chef.cover_thumb('library_edit_modal_cover')
            })

        except Exception, e:
            return Response({
                'success': False,
                'error': e
            },
                            status=status.HTTP_400_BAD_REQUEST)
示例#25
0
def thumbnail_url_(source, alias):
    alias_data = settings.THUMBNAIL_ALIASES[''][alias]
    height = alias_data['size'][0]
    width = alias_data['size'][1]
    try:
        from django.core.files.storage import default_storage
        if source and hasattr(source, 'path') and default_storage.exists(
                source.path):
            return thumbnail_url(source, alias)
        else:
            #return "https://via.placeholder.com/{}x{}".format(height, width)
            return " "
    except ValueError:
        return " "
    def to_representation(self, instance, request=None):
        request = request or self.context.get('request', None)

        if not request:
            raise RuntimeError(
                'Request object must be passed to the field within context '
                'data.')

        if not instance:
            return None

        thumbnail_path = thumbnail_url(instance, self._thumbnail_size)
        absolute_url = request.build_absolute_uri(
            thumbnail_path) if thumbnail_path else ''

        return absolute_url
示例#27
0
def file_upload(request, ftype):
    response = {'OK': 0}
    if request.method == 'POST':
        print(request.FILES)
        print(request.POST)
        if ftype == 'video':
            form = VideoAttachmentForm(request.POST, request.FILES)

        else:  # image
            form = ImageAttachmentForm(request.POST, request.FILES)
        if form.is_valid():
            obj = form.save(commit=False)
            obj.save()
            thumb = thumbnail_url(obj.file, 'photo') if ftype != 'video' else ""
            response = {'OK': 1, 'id': obj.id, 'url': thumb, 'name': re.sub("_[^_]*(?=\.[^\.]*$)", "", basename(obj.file.name))}
        else:
            response['error'] = form.errors['file']
    return HttpResponse(json.dumps(response), content_type="application/json")
示例#28
0
    def render(self, name, value, attrs=None):

        if value is None:
            value = ''
            photo_src = ''
        else:
            photo = Photo.objects.get(id=value)
            photo_src = thumbnail_url(photo.image, 'img')

        final_attrs = self.build_attrs(attrs, type=self.input_type, name=name)
        if value != '':
            # Only add the 'value' attribute if a value is non-empty.
            final_attrs['value'] = force_text(self._format_value(value))

        if not photo_src:
            photo_src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="

        final_attrs.update({'type': 'hidden'})

        return format_html('<div class="row"><div class="col-sm-6"><img class="img-responsive" src="{0}" id="id_image_img" /></div><div class="col-sm-6"><button class="btn btn-primary" type="button" onclick="openGalleryPopup();">Pick image</button><input{1} /></div></div>', photo_src, flatatt(final_attrs))
示例#29
0
def thumbnail_missing(image, alias=False):
    if alias:
        alias_data = settings.THUMBNAIL_ALIASES[''][alias]
        height = alias_data['size'][0]
        width = alias_data['size'][1]
    try:
        from django.core.files.storage import default_storage
        if image and hasattr(image, 'path') and default_storage.exists(
                image.path):
            if alias:
                return thumbnail_url(image.url, alias)
            return image.url
        else:
            if alias:
                return "https://via.placeholder.com/{}x{}".format(
                    height, width)
            return "https://via.placeholder.com/150x150"
    except ValueError:
        if alias:
            return "https://via.placeholder.com/{}x{}".format(height, width)
    return "https://via.placeholder.com/150x150"
示例#30
0
 def map_properties(self):
     # for buildings, link to the building for the name and url
     # but still include the image and address from the place
     if self.building:
         properties = {
             "building_id": self.building.id,
             "url": self.building.get_absolute_url(),
             "title": self.building.title,
         }
     else:
         properties = {
             "url": self.get_absolute_url(),
             "title": self.title,
         }
     properties["id"] = self.id
     image = self.featured_image()
     if image:
         properties["image"] = thumbnail_url(image.image, 'map_thumbnail')
     if self.current_address():
         properties["address"] = self.current_address().address
     return properties
示例#31
0
    def render(self, name, value, attrs=None):

        if value is None:
            value = ''
            photo_src = ''
        else:
            photo = Photo.objects.get(id=value)
            photo_src = thumbnail_url(photo.image, 'img')

        final_attrs = self.build_attrs(attrs, type=self.input_type, name=name)
        if value != '':
            # Only add the 'value' attribute if a value is non-empty.
            final_attrs['value'] = force_text(self._format_value(value))

        if not photo_src:
            photo_src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="

        final_attrs.update({'type': 'hidden'})

        return format_html(
            '<div class="row"><div class="col-sm-6"><img class="img-responsive" src="{0}" id="id_image_img" /></div><div class="col-sm-6"><button class="btn btn-primary" type="button" onclick="openGalleryPopup();">Pick image</button><input{1} /></div></div>',
            photo_src, flatatt(final_attrs))
示例#32
0
 def get_photo_thumb(self, obj):
     return thumbnail_url(obj.photo, 'product_app_thumb')
示例#33
0
def thumbnail_url(source, alias):
    return _thumbnail.thumbnail_url(source, alias)
 def image_thumb_url(self, obj):
     url = thumbnail_url(obj.image, 'poster_index')
     return self.context['request'].build_absolute_uri(url)
示例#35
0
    def to_representation(self, instance):

        if not instance:
            return

        return '{}{}'.format(SITE_URL, thumbnail_url(instance, 'thumbnail_240'))
示例#36
0
def parliament_summary(parliament):
    summary = {
        'nome':
        parliament.nome + ', ' + parliament.municipio.uf.sigla,
        'thumb':
        thumbnail_url(parliament.foto, 'small'),
        'foto': (parliament.foto.url if parliament.foto else ''),
        'lat':
        str(parliament.municipio.latitude),
        'lng':
        str(parliament.municipio.longitude),
        'estado':
        parliament.municipio.uf.sigla,
        'regiao':
        parliament.municipio.uf.regiao,
        'gerente': (str(parliament.gerente_contas.id)
                    if parliament.gerente_contas else ''),
        'diagnosticos': [],
        'seit': [],
        'convenios': [],
        'equipadas': [],
        'info': []
    }

    if parliament.gerente_contas:
        summary['info'].append(
            _(u"Gerente de relacionamento: %s") %
            parliament.gerente_contas.nome_completo)

    for sv in parliament.servico_set.filter(data_desativacao=None):
        summary['info'].append(
            _(u"%(name)s ativado em %(date)s") %
            dict(name=sv.tipo_servico.nome,
                 date=sv.data_ativacao.strftime('%d/%m/%Y') if sv.
                 data_ativacao else _(u'<sem data de ativação>')) +
            " <a href='%s' target='_blank'><img src='%simg/link.gif' alt='link'></a>"
            % (sv.url, STATIC_URL))
        summary['seit'].append(sv.tipo_servico.sigla)

    for cv in parliament.convenio_set.all():
        if (cv.data_retorno_assinatura is
                None) and (cv.equipada and cv.data_termo_aceite is not None):
            summary['info'].append(
                _(u"Equipada em %(date)s pelo %(project)s") %
                dict(date=cv.data_termo_aceite.strftime('%d/%m/%Y'),
                     project=cv.projeto.sigla))
            summary['equipadas'].append(cv.projeto.sigla)
        elif cv.data_retorno_assinatura is None:
            summary['info'].append(
                _(u"Adesão ao projeto %(project)s, em %(date)s") %
                dict(project=cv.projeto.sigla, date=cv.data_adesao))
            summary['convenios'].append(cv.projeto.sigla)
        if (cv.data_retorno_assinatura is not None
            ) and not (cv.equipada and cv.data_termo_aceite is not None):
            summary['info'].append(
                _(u"Conveniada ao %(project)s em %(date)s") %
                dict(project=cv.projeto.sigla,
                     date=cv.data_retorno_assinatura.strftime('%d/%m/%Y')))
            summary['convenios'].append(cv.projeto.sigla)
        if (cv.data_retorno_assinatura
                is not None) and (cv.equipada
                                  and cv.data_termo_aceite is not None):
            summary['info'].append(
                _(u"Conveniada ao %(project)s em %(date)s e equipada em %(equipped_date)s"
                  ) %
                dict(project=cv.projeto.sigla,
                     date=cv.data_retorno_assinatura.strftime('%d/%m/%Y'),
                     equipped_date=cv.data_termo_aceite.strftime('%d/%m/%Y')))
            summary['equipadas'].append(cv.projeto.sigla)
            summary['convenios'].append(cv.projeto.sigla)

    for dg in parliament.diagnostico_set.all():
        summary['diagnosticos'].append('P' if dg.publicado else 'A')
        summary['info'].append(
            _(u'Diagnosticada no período de %(initial_date)s a %(final_date)s')
            % dict(initial_date=dg.data_visita_inicio.strftime('%d/%m/%Y')
                   if dg.data_visita_inicio is not None else
                   _(u"<sem data de início>"),
                   final_date=dg.data_visita_fim.strftime('%d/%m/%Y')
                   if dg.data_visita_fim else _(u"<sem data de término>")))

    return summary
示例#37
0
 def get_image_thumb(self, obj):
     try:
         return thumbnail_url(obj.image, 'banner_explore_thumb')
     except:
         return ''
示例#38
0
def thumbnail_url(source, alias):
    return _thumbnail.thumbnail_url(source, alias)
示例#39
0
def recipe(request, slug, id):
    recipe_application_service = RecipeApplicationService.new()
    book_application_service = BookApplicationService.new()
    # Sanitize input, if we don't get id redirect permanent to home page
    try:
        recipe_id = int(id)
        cache = get_cache('default')
        recipe_key = CacheUtils.get_key(CacheUtils.RECIPE, recipe_id=recipe_id)
        recipe = cache.get(recipe_key, None)
        if recipe is None:
            recipe = Recipes.objects.select_related('chef').get(id=recipe_id)
            cache.set(recipe_key, recipe)
    except (ValueError, Recipes.DoesNotExist):
        raise Http404()

    is_chef_or_collaborator = False

    if not recipe_application_service.is_recipe_available_for_chef(
            recipe.id, request.user.id):

        if request.user.is_authenticated():
            allowed = False
            chef_added_book_ids = request.user.books_added.all().values_list(
                'id', flat=True)
            recipe_book_ids = BookHasRecipes.objects.filter(
                recipe=recipe).values_list('book', flat=True)
            for chef_added_book_id in chef_added_book_ids:
                if chef_added_book_id in recipe_book_ids:
                    allowed = True
                    break
            if not allowed:
                raise PermissionDenied()
        else:
            raise PermissionDenied()
    elif recipe.draft == 1 and recipe.chef != request.user:
        raise PermissionDenied()

    elif recipe.draft == 1 and recipe.chef == request.user:
        return HttpResponseRedirect(
            reverse('kitchen_draft', kwargs={'id': recipe.id}))

    # Hide the sections of the page that you will see after you pay
    hide_to_sell = False

    # Hide the sections of the page of a normal recipe
    book_to_sell_recipe = False

    book_to_sell = None
    chef_has_book = None
    book_to_sell_has_recipes = []

    if not request.GET.has_key('view') and not request.GET.get(
            'view') == 'premium':
        books = BookHasRecipes.objects.filter(recipe=recipe,
                                              book__book_type=Book.TO_SELL)
        if books.exists():
            book_to_sell = books[0].book
            book_to_sell_recipe = True
            hide_to_sell = True

            book_to_sell_has_recipes = BookHasRecipes.objects.filter(
                book=book_to_sell)  # .exclude(recipe=recipe)
            if request.user.is_authenticated():
                try:
                    chef_has_book = ChefsHasBooks.objects.get(
                        chef=request.user, book=book_to_sell)
                    hide_to_sell = False
                except:
                    pass

    recipe_cover_key = CacheUtils.get_key(CacheUtils.RECIPE_COVER,
                                          recipe_id=recipe_id)
    recipe_cover = cache.get(recipe_cover_key, None)
    if recipe_cover is None:
        recipe_cover = thumbnail_url(recipe.cover, 'explore_cover')
        cache.set(recipe_cover_key, recipe_cover)

    recipe_steps_key = CacheUtils.get_key(CacheUtils.RECIPE_STEPS,
                                          recipe_id=recipe_id)
    recipe_steps = cache.get(recipe_steps_key, None)
    if recipe_steps is None:
        recipe_steps = []
        for step in recipe.photos.all():
            step_thumb_small = thumbnail_url(step.image, 'recipe_step')
            step_thumb_big = thumbnail_url(step.image, 'recipe_step_full_size')
            recipe_steps.append(
                dict(
                    instructions=step.instructions,
                    photo_order=step.photo_order,
                    step_thumb_small=step_thumb_small,
                    step_thumb_big=step_thumb_big,
                ))
        cache.set(recipe_steps_key, recipe_steps)

    recipe_ingredients_key = CacheUtils.get_key(CacheUtils.RECIPE_INGREDIENTS,
                                                recipe_id=recipe_id)
    recipe_ingredients = cache.get(recipe_ingredients_key, None)
    if recipe_ingredients is None:
        recipe_ingredients = recipe.get_sorted_ingredients()
        cache.set(recipe_ingredients_key, recipe_ingredients)

    recipe_tags_keys = CacheUtils.get_key(CacheUtils.RECIPE_TAGS,
                                          recipe_id=recipe_id)
    recipe_tags = cache.get(recipe_tags_keys, None)
    if recipe_tags is None:
        recipe_tags = recipe.tags.all()
        cache.set(recipe_tags_keys, recipe_tags)

    recipe_comments_key = CacheUtils.get_key(CacheUtils.RECIPE_COMMENTS,
                                             recipe_id=recipe_id)
    recipe_comments = cache.get(recipe_comments_key, None)
    if recipe_comments is None:
        recipe_comments = recipe.comments.select_related('chef').all()
        cache.set(recipe_comments_key, recipe_comments)

    recipe_products_key = CacheUtils.get_key(CacheUtils.RECIPE_PRODUCTS,
                                             recipe_id=recipe_id)
    recipe_products = cache.get(recipe_products_key, None)
    if recipe_products is None:
        recipe_products = recipe.products.all()
        cache.set(recipe_products_key, recipe_products)

    chef = recipe.chef
    other_recipes = recipe_application_service.get_recipes_for_explore(
        request.user)[:4]
    print(other_recipes)

    chef_followings_key = CacheUtils.get_key(
        CacheUtils.CHEF_FOLLOWINGS_LIST_10, chef_id=chef.id)
    chef_followings = cache.get(chef_followings_key, None)
    if chef_followings is None:
        temp_followings = chef.following.all()[:10]
        serializer = LibraryChefSerializer(temp_followings, many=True)
        temp_serialized = serializer.data
        cache.set(chef_followings_key, temp_serialized)
        chef_followings = temp_serialized[:4]
    else:
        chef_followings = chef_followings[:4]

    chef_avatar_key = CacheUtils.get_key(CacheUtils.CHEF_AVATAR,
                                         chef_id=chef.id)
    chef_avatar = cache.get(chef_avatar_key, None)
    if chef_avatar is None:
        if chef.avatar:
            chef_avatar = thumbnail_url(chef.avatar, 'chef_avatar')
            cache.set(chef_avatar_key, chef_avatar)

    site = Site.objects.get_current()

    user_books_json = []
    recipe_in_books_json = []
    related_recipes = []
    show_private = False
    if request.user.is_authenticated():
        user_books_json = None
        recipe_in_books_json = None
        if user_books_json is None:
            user_books = request.user.books.all()
            user_books_json = json.dumps(
                WebRecipeBookSerializer(user_books).data)

        if recipe_in_books_json is None:
            recipe_in_books = BookHasRecipes.objects.values_list(
                'book_id', flat=True).filter(recipe=recipe,
                                             book__chef=request.user)
            recipe_in_books_json = []
            for rib in recipe_in_books:
                recipe_in_books_json.append(rib)
            recipe_in_books_json = json.dumps(recipe_in_books_json)

            # related_recipes_key = CacheUtils.get_key(CacheUtils.CHEF_RELATED_RECIPES_5, chef_id=chef.id)
            # related_recipes = cache.get(related_recipes_key, None)
            # if related_recipes is None:
            #     chef = recipe.chef
            #     show_private = chef == request.user
            #     books = Book.objects.all_books(chef, show_private=show_private)
            #     related_recipes = recipe_application_service.get_recipe_by_books(books)
            #     cache.set(related_recipes_key, related_recipes)

        chef = recipe.chef

        show_private = chef == request.user

        if chef == request.user:
            books = book_application_service.get_book_by_chef(chef)
        else:
            books = Book.objects.all_books(chef, show_private=show_private)
            collaborated_books = book_application_service.getBooksByCollaborator(
                chef, request.user) if request.user.id else list()
            books = list(chain(books, collaborated_books))
            books = list(set(books))

        related_recipes = recipe_application_service.get_visible_recipes(
            request.user.id, chef.id)

    try:
        chef = Chefs.objects.get(pk=chef.id)
    except:
        chef = chef

    is_collaborator = book_application_service.check_chef_is_collaborator_of_recipe(
        request.user, recipe)
    allergens = recipe_application_service.get_allergens_for_recipe(recipe.id)
    if chef == request.user or is_collaborator:
        is_chef_or_collaborator = True
    else:
        is_chef_or_collaborator = False

    allow_see_pricing = False
    if request.user.is_authenticated() and (
            request.user.membership == 'default'
            or request.user.membership == 'pro'):
        allow_see_pricing = False
    else:
        allow_see_pricing = True

    response = dict(
        recipe=recipe,
        chef=chef,
        hide_to_sell=hide_to_sell,
        book_to_sell=book_to_sell,
        book_to_sell_recipe=book_to_sell_recipe,
        book_to_sell_has_recipes=book_to_sell_has_recipes,
        chef_has_book=chef_has_book,
        chef_avatar=chef_avatar,
        recipe_cover=recipe_cover,
        recipe_steps=recipe_steps,
        recipe_ingredients=recipe_ingredients,
        recipe_tags=recipe_tags,
        recipe_comments=recipe_comments,
        recipe_products=recipe_products,
        related_recipes=related_recipes,
        chef_followings=chef_followings,
        other_recipes=other_recipes,
        SITE=site,
        user_books=user_books_json,
        recipe_in_books=recipe_in_books_json,
        is_chef_or_collaborator=is_chef_or_collaborator,
        allow_see_pricing=allow_see_pricing,
        owner=show_private,
        allergens=allergens,
    )
    return render_to_response('recipe/recipe.html',
                              response,
                              context_instance=RequestContext(request))