示例#1
0
文件: ajax.py 项目: ksenor/nnmware
 def _ajax_upload(self, request, **kwargs):
     if request.method == "POST":
         self._upload_file(request, **kwargs)
         fullpath = os.path.join(settings.MEDIA_ROOT, self.extra_context["path"])
         try:
             i = Image.open(fullpath)
         except:
             messages.error(request, "File is not image format")
             os.remove(fullpath)
             self.success = False
             self.pic_id = None
             addons = None
         if self.success:
             new = Pic()
             self._new_obj(new, request, **kwargs)
             new.pic = self.extra_context["path"]
             fullpath = os.path.join(settings.MEDIA_ROOT, new.pic.field.upload_to, new.pic.path)
             new.size = os.path.getsize(fullpath)
             new.save()
             self.pic_id = new.pk
             # let Ajax Upload know whether we saved it or not
             addons = {
                 "size": os.path.getsize(fullpath),
                 "thumbnail": make_thumbnail(new.pic.url, width=settings.DEFAULT_UPLOAD_THUMBNAIL_SIZE),
             }
         payload = {"success": self.success, "filename": self.filename, "id": self.pic_id}
         if self.extra_context is not None:
             payload.update(self.extra_context)
         if addons:
             payload.update(addons)
         return AjaxAnswer(payload)
示例#2
0
 def _ajax_upload(self, request, **kwargs):
     if request.method == "POST":
         tmb = None
         self._upload_file(request, **kwargs)
         fullpath = os.path.join(settings.MEDIA_ROOT, self.extra_context['path'])
         try:
             i = Image.open(fullpath)
         except:
             messages.error(request, "File is not image format")
             os.remove(fullpath)
             self.success = False
             self.pic_id = None
         if self.success:
             ctype = get_object_or_404(ContentType, id=int(kwargs['content_type']))
             object_id = int(kwargs['object_id'])
             obj = ctype.get_object_for_this_type(pk=object_id)
             try:
                 remove_thumbnails(obj.img.path)
                 remove_file(obj.img.path)
                 obj.img.delete()
             except:
                 pass
             obj.img = self.extra_context['path']
             obj.save()
             # let Ajax Upload know whether we saved it or not
             addons = {'tmb': make_thumbnail(obj.img.url, width=int(kwargs['width']), height=int(kwargs['height']),
                                             aspect=int(kwargs['aspect']))}
         payload = {'success': self.success, 'filename': self.filename}
         if self.extra_context is not None:
             payload.update(self.extra_context)
         if addons:
             payload.update(addons)
         return AjaxAnswer(payload)
示例#3
0
def file_uploader(request, **kwargs):
    uploader = AjaxUploader(
        filetype="image",
        uploadDirectory=setting("IMAGE_UPLOAD_DIR", "images"),
        sizeLimit=setting("IMAGE_UPLOAD_SIZE", 10485760),
    )
    result = uploader.handleUpload(request)
    if result["success"]:
        ctype = get_object_or_404(ContentType, id=int(kwargs["content_type"]))
        object_id = int(kwargs["object_id"])
        obj = ctype.get_object_for_this_type(pk=object_id)
        try:
            remove_thumbnails(obj.img.path)
            remove_file(obj.img.path)
            obj.img.delete()
        except:
            pass
        obj.img = result["path"]
        obj.save()
        try:
            addons = dict(
                tmb=make_thumbnail(
                    obj.img.url, width=int(kwargs["width"]), height=int(kwargs["height"]), aspect=int(kwargs["aspect"])
                )
            )
        except:
            addons = {}
        result.update(addons)
    return AjaxAnswer(result)
示例#4
0
文件: ajax.py 项目: kingctan/nnmware
def add_related_product(request, object_id):
    try:
        if not request.user.is_superuser:
            raise AccessError
        p = get_object_or_404(Product, pk=int(object_id))
        product = get_object_or_404(Product, pk=int(request.POST["product"]))
        p.related_products.add(product)
        p.save()
        payload = {
            "success": True,
            "name": product.name,
            "id": product.pk,
            "url": product.get_absolute_url(),
            "src": make_thumbnail(
                product.main_image,
                width=settings.RELATED_PRODUCT_WIDTH,
                height=settings.RELATED_PRODUCT_HEIGHT,
                aspect=1,
            ),
        }
    except AccessError:
        payload = {"success": False}
    except:
        payload = {"success": False}
    return AjaxLazyAnswer(payload)
示例#5
0
 def _ajax_upload(self, request, **kwargs):
     if request.method == "POST":
         self._upload_file(request, **kwargs)
         fullpath = os.path.join(settings.MEDIA_ROOT,
                                 self.extra_context['path'])
         try:
             i = Image.open(fullpath)
         except:
             messages.error(request, "File is not image format")
             os.remove(fullpath)
             self.success = False
             self.pic_id = None
             addons = None
         if self.success:
             new = Pic()
             self._new_obj(new, request, **kwargs)
             new.pic = self.extra_context['path']
             fullpath = os.path.join(settings.MEDIA_ROOT,
                                     new.pic.field.upload_to, new.pic.path)
             new.size = os.path.getsize(fullpath)
             new.save()
             self.pic_id = new.pk
             # let Ajax Upload know whether we saved it or not
             addons = {'size': os.path.getsize(fullpath),
                       'thumbnail': make_thumbnail(new.pic.url, width=settings.DEFAULT_THUMBNAIL_WIDTH,
                                                   height=settings.DEFAULT_THUMBNAIL_HEIGHT, aspect=1)}
         payload = {'success': self.success, 'filename': self.filename, 'id': self.pic_id}
         if self.extra_context is not None:
             payload.update(self.extra_context)
         if addons:
             payload.update(addons)
         return AjaxAnswer(payload)
示例#6
0
文件: abstract.py 项目: krast/nnmware
 def slide_thumbnail(self):
     if self.img:
         path = self.img.url
         tmb = make_thumbnail(path, width=60, height=60, aspect=1)
     else:
         tmb = '/static/img/icon-no.gif"'
         path = '/static/img/icon-no.gif"'
     return '<a target="_blank" href="%s"><img src="%s" /></a>' % (path, tmb)
示例#7
0
文件: ajax.py 项目: cihatkk/nnmware
def img_getcrop(request, object_id):
    # Link used for User want crop image
    pic = get_object_or_404(Pic, id=int(object_id))
    try:
        payload = dict(success=True, src=make_thumbnail(pic.pic.url, width=MAX_IMAGE_CROP_WIDTH), id=pic.pk)
    except:
        payload = dict(success=False)
    return ajax_answer_lazy(payload)
示例#8
0
文件: abstract.py 项目: krast/nnmware
 def thumbnail(self):
     if self.img:
         path = self.img.url
         tmb = make_thumbnail(path, height=60, width=60)
         return '<a style="display:block;text-align:center;" target="_blank" href="%s"><img src="%s" /></a>' \
                '<p style="text-align:center;margin-top:5px;">%sx%s px</p>' % (path, tmb, self.img_width,
                                                                               self.img_height)
     return "No image"
示例#9
0
def pic_getcrop(request, object_id):
    # Link used for User want crop image
    pic = get_object_or_404(Pic, id=int(object_id))
    try:
        payload = dict(success=True, src=make_thumbnail(pic.pic.url, width=settings.MAX_IMAGE_CROP_WIDTH), id=pic.pk)
    except:
        payload = {'success': False}
    return AjaxLazyAnswer(payload)
示例#10
0
文件: ajax.py 项目: ksenor/nnmware
def img_getcrop(request, object_id):
    # Link used for User want crop image
    pic = get_object_or_404(Pic, id=int(object_id))
    try:
        payload = {
            "success": True,
            "src": make_thumbnail(pic.pic.url, width=settings.MAX_IMAGE_CROP_WIDTH),
            "id": pic.pk,
        }
    except:
        payload = {"success": False}
    return AjaxLazyAnswer(payload)
示例#11
0
def img_setmain(request, object_id, img_w='64', img_h='64'):
    # Link used for User press SetMain for Image
    pic = get_object_or_404(Pic, id=int(object_id))
    if img_check_rights(request, pic):
        all_pics = Pic.objects.for_object(pic.content_object)
        all_pics.update(primary=False)
        pic.primary = True
        pic.save()
        payload = {'success': True, 'src': make_thumbnail(pic.pic.url, width=int(img_w), height=int(img_h), aspect=1)}
    else:
        payload = {'success': False}
    return ajax_answer_lazy(payload)
示例#12
0
def img_getcrop(request, object_id):
    # Link used for User want crop image
    pic = get_object_or_404(Pic, id=int(object_id))
    # noinspection PyBroadException
    try:
        payload = dict(success=True,
                       src=make_thumbnail(pic.pic.url,
                                          width=MAX_IMAGE_CROP_WIDTH),
                       id=pic.pk)
    except:
        payload = dict(success=False)
    return ajax_answer_lazy(payload)
示例#13
0
文件: ajax.py 项目: MrTomato8/nnmware
def autocomplete_search(request,size=16):
    results = []
    search_qs = Product.objects.filter(
        Q(name__icontains=request.REQUEST['q']) |
        Q(name_en__icontains=request.REQUEST['q'])).order_by('name')[:5]
    for r in search_qs:
        img = make_thumbnail(r.main_image,width=int(size))
        userstring = {'name': r.name, 'path': r.get_absolute_url(),
                      'img': img,
                      'slug': r.slug, 'amount':"%0.2f" % (r.amount,),'id':r.pk }
        results.append(userstring)
    payload = {'answer': results}
    return AjaxLazyAnswer(payload)
示例#14
0
def autocomplete_search(request, size=16):
    results = []
    search_qs = Product.objects.filter(
        Q(name__icontains=request.POST['q']) |
        Q(name_en__icontains=request.POST['q'])).order_by('name')[:5]
    for r in search_qs:
        img = make_thumbnail(r.main_image, width=int(size))
        userstring = {'name': r.name, 'path': r.get_absolute_url(),
                      'img': img,
                      'slug': r.slug, 'amount': "%0.2f" % (r.amount,), 'id': r.pk}
        results.append(userstring)
    payload = {'answer': results}
    return AjaxLazyAnswer(payload)
示例#15
0
def thumbnail(url, args=''):
    """ Returns thumbnail URL and create it if not already exists.
Usage::

    {{ url|thumbnail:"width=10,height=20" }}
    {{ url|thumbnail:"width=10" }}
    {{ url|thumbnail:"height=20,aspect=1" }}

Image is **proportionally** resized to dimension which is no greater than ``width x height``.

Thumbnail file is saved in the same location as the original image
and his name is constructed like this::

    %(dirname)s/%(basename)s_t[_w%(width)d][_h%(height)d].%(extension)s

or if only a width is requested (to be compatibile with admin interface)::

    %(dirname)s/%(basename)s_t%(width)d.%(extension)s

"""
    if url is None:
        return None
    kwargs = {}
    if args:
        if ',' not in args:
            # ensure at least one ','
            args += ','
        for arg in args.split(','):
            arg = arg.strip()
            if arg == '':
                continue
            kw, val = arg.split('=', 1)
            kw = kw.lower().encode('ascii')
            try:
                val = int(val)  # convert all ints
            except ValueError:
                raise TemplateSyntaxError
            kwargs[kw] = val

    if ('width' not in kwargs) and ('height' not in kwargs):
        raise TemplateSyntaxError

    ret = make_thumbnail(url, **kwargs)
    if ret is None:
        ret = url

    if not ret.startswith(settings.MEDIA_URL):
        ret = settings.MEDIA_URL + ret

    return ret
示例#16
0
文件: ajax.py 项目: cihatkk/nnmware
def ajax_get_thumbnail(request):
    img_pk = int(request.POST['image_id'])
    pic = get_object_or_404(Pic, id=int(img_pk))
    width = request.POST.get('width') or None
    height = request.POST.get('height') or None
    if width:
        width = int(width)
    if height:
        height = int(height)
    try:
        payload = dict(success=True, src=make_thumbnail(pic.pic.url, width=width, height=height), id=pic.pk)
    except:
        payload = {'success': False}
    return ajax_answer_lazy(payload)
示例#17
0
def AjaxGetThumbnail(request):
    img_pk = int(request.POST["image_id"])
    pic = get_object_or_404(Pic, id=int(img_pk))
    width = request.POST.get("width") or None
    height = request.POST.get("height") or None
    if width:
        width = int(width)
    if height:
        height = int(height)
    try:
        payload = dict(success=True, src=make_thumbnail(pic.pic.url, width=width, height=height), id=pic.pk)
    except:
        payload = {"success": False}
    return AjaxLazyAnswer(payload)
示例#18
0
def thumbnail(url, args=''):
    """ Returns thumbnail URL and create it if not already exists.
    Usage::

        {{ url|thumbnail:"width=10,height=20" }}
        {{ url|thumbnail:"width=10" }}
        {{ url|thumbnail:"height=20,aspect=1" }}

    Image is **proportionally** resized to dimension which is no greater than ``width x height``.

    Thumbnail file is saved in the same location as the original image
    and his name is constructed like this::

        %(dirname)s/%(basename)s_t[_w%(width)d][_h%(height)d].%(extension)s

    or if only a width is requested (to be compatibile with admin interface)::

        %(dirname)s/%(basename)s_t%(width)d.%(extension)s

    """
    if url is None:
        return None
    kwargs = {}
    if args:
        if ',' not in args:
            # ensure at least one ','
            args += ','
        for arg in args.split(','):
            arg = arg.strip()
            if arg == '':
                continue
            kw, val = arg.split('=', 1)
            kw = kw.lower().encode('ascii')
            try:
                val = int(val)  # convert all ints
            except ValueError:
                raise TemplateSyntaxError
            kwargs[kw] = val

    if ('width' not in kwargs) and ('height' not in kwargs):
        raise TemplateSyntaxError

    ret = make_thumbnail(url, **kwargs)
    if ret is None:
        ret = url

    if not ret.startswith(settings.MEDIA_URL):
        ret = settings.MEDIA_URL + ret

    return ret
示例#19
0
文件: ajax.py 项目: MrTomato8/nnmware
def hotels_in_country(request):
    try:
        results = []
        for hotel in Hotel.objects.all().order_by('starcount'):
            answer = {'name':hotel.get_name, 'latitude':hotel.latitude,'url':hotel.get_absolute_url(),
                      'address':hotel.address,'id':hotel.pk,'starcount':hotel.starcount,
                      'img':make_thumbnail(hotel.main_image,width=113,height=75,aspect=1),
                      'longitude':hotel.longitude, 'starcount_name':hotel.get_starcount_display(),
                      'amount':str(int(hotel.current_amount ))}
            results.append(answer)
        payload = {'success': True, 'hotels':results}
    except :
        payload = {'success': False}
    return AjaxLazyAnswer(payload)
示例#20
0
文件: ajax.py 项目: nnmware/nnmware
def filter_hotels_on_map(request, hotels):
    try:
        searched = hotels
        f_date = request.POST.get("start_date") or None
        amount_min = request.POST.get("amount_min") or None
        amount_max = request.POST.get("amount_max") or None
        options = request.POST.getlist("options") or None
        stars = request.POST.getlist("stars") or None
        if amount_max and amount_min:
            if f_date:
                from_date = convert_to_date(f_date)
                hotels_with_amount = (
                    PlacePrice.objects.filter(date=from_date, amount__range=(amount_min, amount_max))
                    .values_list("settlement__room__hotel__pk", flat=True)
                    .distinct()
                )
            else:
                hotels_with_amount = (
                    PlacePrice.objects.filter(date=now(), amount__range=(amount_min, amount_max))
                    .values_list("settlement__room__hotel__pk", flat=True)
                    .distinct()
                )
            searched = searched.filter(pk__in=hotels_with_amount, work_on_request=False)
        if options:
            for option in options:
                searched = searched.filter(option=option)
        if stars:
            searched = searched.filter(starcount__in=stars)
        searched = searched.order_by("starcount")
        results = []
        for hotel in searched:
            answer = {
                "name": hotel.get_name,
                "latitude": hotel.latitude,
                "url": hotel.get_absolute_url(),
                "address": hotel.address,
                "id": hotel.pk,
                "starcount": hotel.starcount,
                "img": make_thumbnail(hotel.main_image, width=113, height=75, aspect=1),
                "longitude": hotel.longitude,
                "starcount_name": hotel.get_starcount_display(),
                "amount": str(int(hotel.current_amount)),
            }

            results.append(answer)
        payload = {"success": True, "hotels": results}
    except:
        payload = {"success": False}
    return ajax_answer_lazy(payload)
示例#21
0
文件: ajax.py 项目: ir4y/nnmware
def add_related_product(request,object_id):
    try:
        if not request.user.is_superuser:
            raise AccessError
        p = get_object_or_404(Product,pk=int(object_id))
        product = get_object_or_404(Product,pk=int(request.REQUEST['product']))
        p.related_products.add(product)
        p.save()
        payload = {'success': True, 'name':product.name, 'id': product.pk, 'url':product.get_absolute_url(),
                   'src': make_thumbnail(product.main_image,width=settings.RELATED_PRODUCT_WIDTH,height=settings.RELATED_PRODUCT_HEIGHT, aspect=1)}
    except AccessError:
        payload = {'success': False}
    except :
        payload = {'success': False}
    return AjaxLazyAnswer(payload)
示例#22
0
def img_setmain(request, object_id, img_w='64', img_h='64'):
    # Link used for User press SetMain for Image
    pic = get_object_or_404(Pic, id=int(object_id))
    if img_check_rights(request, pic):
        all_pics = Pic.objects.for_object(pic.content_object)
        all_pics.update(primary=False)
        pic.primary = True
        pic.save()
        payload = dict(success=True,
                       src=make_thumbnail(pic.img.url,
                                          width=int(img_w),
                                          height=int(img_h),
                                          aspect=1))
    else:
        payload = dict(success=False)
    return ajax_answer_lazy(payload)
示例#23
0
def add_related_product(request, object_id):
    try:
        if not request.user.is_superuser:
            raise AccessError
        p = get_object_or_404(Product, pk=int(object_id))
        product = get_object_or_404(Product, pk=int(request.POST['product']))
        p.related_products.add(product)
        p.save()
        payload = {'success': True, 'name': product.name, 'id': product.pk, 'url': product.get_absolute_url(),
                   'src': make_thumbnail(product.main_image, width=settings.RELATED_PRODUCT_WIDTH,
                                         height=settings.RELATED_PRODUCT_HEIGHT, aspect=1)}
    except AccessError:
        payload = {'success': False}
    except:
        payload = {'success': False}
    return AjaxLazyAnswer(payload)
示例#24
0
文件: ajax.py 项目: MrTomato8/nnmware
def AjaxGetThumbnail(request):
    img_pk = int(request.REQUEST['image_id'])
    pic = get_object_or_404(Pic, id=int(img_pk))
    width = request.REQUEST.get('width') or None
    height = request.REQUEST.get('height') or None
    if width:
        width = int(width)
    if height:
        height = int(height)
    try:
        payload = {'success': True,
                   'src': make_thumbnail(pic.pic.url,width=width,height=height),
                   'id':pic.pk}
    except :
        payload = {'success': False}
    return AjaxLazyAnswer(payload)
示例#25
0
def add_color(request, object_id):
    try:
        if not request.user.is_superuser:
            raise AccessError
        p = get_object_or_404(Product, pk=int(object_id))
        color = get_object_or_404(ProductColor, pk=int(request.POST['color']))
        w = int(request.POST['width'])
        h = int(request.POST['height'])
        p.colors.add(color)
        p.save()
        payload = {'success': True, 'name': color.name, 'id': color.pk,
                   'src': make_thumbnail(color.img.url, width=w, height=h)}
    except AccessError:
        payload = {'success': False}
    except:
        payload = {'success': False}
    return AjaxLazyAnswer(payload)
示例#26
0
def add_color(request, object_id):
    try:
        if not request.user.is_superuser:
            raise AccessError
        p = get_object_or_404(Product, pk=int(object_id))
        color = get_object_or_404(ProductColor, pk=int(request.REQUEST['color']))
        w = int(request.REQUEST['width'])
        h = int(request.REQUEST['height'])
        p.colors.add(color)
        p.save()
        payload = {'success': True, 'name': color.name, 'id': color.pk,
                   'src': make_thumbnail(color.img.url, width=w, height=h)}
    except AccessError:
        payload = {'success': False}
    except:
        payload = {'success': False}
    return AjaxLazyAnswer(payload)
示例#27
0
def add_color(request, object_id):
    # noinspection PyBroadException
    try:
        if not request.user.is_superuser:
            raise AccessError
        p = get_object_or_404(Product, pk=int(object_id))
        color = get_object_or_404(ProductColor, pk=int(request.POST['color']))
        w = int(request.POST['width'])
        h = int(request.POST['height'])
        p.colors.add(color)
        p.save()
        payload = {'success': True, 'name': color.name, 'id': color.pk,
                   'src': make_thumbnail(color.img.url, width=w, height=h)}
    except AccessError as aerr:
        payload = dict(success=False)
    except:
        payload = dict(success=False)
    return ajax_answer_lazy(payload)
示例#28
0
文件: ajax.py 项目: kingctan/nnmware
def autocomplete_search(request, size=16):
    results = []
    search_qs = Product.objects.filter(
        Q(name__icontains=request.POST["q"]) | Q(name_en__icontains=request.POST["q"])
    ).order_by("name")[:5]
    for r in search_qs:
        img = make_thumbnail(r.main_image, width=int(size))
        userstring = {
            "name": r.name,
            "path": r.get_absolute_url(),
            "img": img,
            "slug": r.slug,
            "amount": "%0.2f" % (r.amount,),
            "id": r.pk,
        }
        results.append(userstring)
    payload = {"answer": results}
    return AjaxLazyAnswer(payload)
示例#29
0
文件: ajax.py 项目: ukaoma/nnmware
def AjaxGetThumbnail(request):
    img_pk = int(request.POST['image_id'])
    pic = get_object_or_404(Pic, id=int(img_pk))
    width = request.POST.get('width') or None
    height = request.POST.get('height') or None
    if width:
        width = int(width)
    if height:
        height = int(height)
    try:
        payload = dict(success=True,
                       src=make_thumbnail(pic.pic.url,
                                          width=width,
                                          height=height),
                       id=pic.pk)
    except:
        payload = {'success': False}
    return AjaxLazyAnswer(payload)
示例#30
0
def add_color(request, object_id):
    # noinspection PyBroadException
    try:
        if not request.user.is_superuser:
            raise AccessError
        p = get_object_or_404(Product, pk=int(object_id))
        color = get_object_or_404(ProductColor, pk=int(request.POST['color']))
        w = int(request.POST['width'])
        h = int(request.POST['height'])
        p.colors.add(color)
        p.save()
        payload = {'success': True, 'name': color.name, 'id': color.pk,
                   'src': make_thumbnail(color.img.url, width=w, height=h)}
    except AccessError as aerr:
        payload = {'success': False}
    except:
        payload = {'success': False}
    return ajax_answer_lazy(payload)
示例#31
0
文件: ajax.py 项目: bbotte/nnmware
def ajax_get_thumbnail(request):
    img_pk = int(request.POST['image_id'])
    pic = get_object_or_404(Pic, id=int(img_pk))
    width = request.POST.get('width') or None
    height = request.POST.get('height') or None
    if width:
        width = int(width)
    if height:
        height = int(height)
    # noinspection PyBroadException
    try:
        payload = dict(success=True,
                       src=make_thumbnail(pic.pic.url,
                                          width=width,
                                          height=height),
                       id=pic.pk)
    except:
        payload = {'success': False}
    return ajax_answer_lazy(payload)
示例#32
0
文件: ajax.py 项目: ukaoma/nnmware
 def _ajax_upload(self, request, **kwargs):
     if request.method == "POST":
         self._upload_file(request, **kwargs)
         fullpath = os.path.join(settings.MEDIA_ROOT,
                                 self.extra_context['path'])
         try:
             i = Image.open(fullpath)
         except:
             messages.error(request, "File is not image format")
             os.remove(fullpath)
             self.success = False
             self.pic_id = None
             addons = None
         if self.success:
             new = Pic()
             self._new_obj(new, request, **kwargs)
             new.pic = self.extra_context['path']
             fullpath = os.path.join(settings.MEDIA_ROOT,
                                     new.pic.field.upload_to, new.pic.path)
             new.size = os.path.getsize(fullpath)
             new.save()
             self.pic_id = new.pk
             # let Ajax Upload know whether we saved it or not
             addons = {
                 'size':
                 os.path.getsize(fullpath),
                 'thumbnail':
                 make_thumbnail(new.pic.url,
                                width=settings.DEFAULT_THUMBNAIL_WIDTH,
                                height=settings.DEFAULT_THUMBNAIL_HEIGHT,
                                aspect=1)
             }
         payload = {
             'success': self.success,
             'filename': self.filename,
             'id': self.pic_id
         }
         if self.extra_context is not None:
             payload.update(self.extra_context)
         if addons:
             payload.update(addons)
         return AjaxAnswer(payload)
示例#33
0
文件: ajax.py 项目: ukaoma/nnmware
def img_setmain(request, object_id, img_w='64', img_h='64'):
    # Link used for User press SetMain for Image
    pic = get_object_or_404(Pic, id=int(object_id))
    if img_check_rights(request, pic):
        all_pics = Pic.objects.for_object(pic.content_object)
        all_pics.update(primary=False)
        pic.primary = True
        pic.save()
        payload = {
            'success':
            True,
            'src':
            make_thumbnail(pic.pic.url,
                           width=int(img_w),
                           height=int(img_h),
                           aspect=1)
        }
    else:
        payload = {'success': False}
    return AjaxLazyAnswer(payload)
示例#34
0
文件: ajax.py 项目: kingctan/nnmware
def add_color(request, object_id):
    try:
        if not request.user.is_superuser:
            raise AccessError
        p = get_object_or_404(Product, pk=int(object_id))
        color = get_object_or_404(ProductColor, pk=int(request.POST["color"]))
        w = int(request.POST["width"])
        h = int(request.POST["height"])
        p.colors.add(color)
        p.save()
        payload = {
            "success": True,
            "name": color.name,
            "id": color.pk,
            "src": make_thumbnail(color.img.url, width=w, height=h),
        }
    except AccessError:
        payload = {"success": False}
    except:
        payload = {"success": False}
    return AjaxLazyAnswer(payload)
示例#35
0
文件: ajax.py 项目: ukaoma/nnmware
 def _ajax_upload(self, request, **kwargs):
     if request.method == "POST":
         tmb = None
         self._upload_file(request, **kwargs)
         fullpath = os.path.join(settings.MEDIA_ROOT,
                                 self.extra_context['path'])
         try:
             i = Image.open(fullpath)
         except:
             messages.error(request, "File is not image format")
             os.remove(fullpath)
             self.success = False
             self.pic_id = None
         if self.success:
             ctype = get_object_or_404(ContentType,
                                       id=int(kwargs['content_type']))
             object_id = int(kwargs['object_id'])
             obj = ctype.get_object_for_this_type(pk=object_id)
             try:
                 remove_thumbnails(obj.img.path)
                 remove_file(obj.img.path)
                 obj.img.delete()
             except:
                 pass
             obj.img = self.extra_context['path']
             obj.save()
             # let Ajax Upload know whether we saved it or not
             addons = {
                 'tmb':
                 make_thumbnail(obj.img.url,
                                width=int(kwargs['width']),
                                height=int(kwargs['height']),
                                aspect=int(kwargs['aspect']))
             }
         payload = {'success': self.success, 'filename': self.filename}
         if self.extra_context is not None:
             payload.update(self.extra_context)
         if addons:
             payload.update(addons)
         return AjaxAnswer(payload)
示例#36
0
def filter_hotels_on_map(request, hotels):
    try:
        searched = hotels
        f_date = request.POST.get('start_date') or None
        amount_min = request.POST.get('amount_min') or None
        amount_max = request.POST.get('amount_max') or None
        options = request.POST.getlist('options') or None
        stars = request.POST.getlist('stars') or None
        if amount_max and amount_min:
            if f_date:
                from_date = convert_to_date(f_date)
                hotels_with_amount = PlacePrice.objects.filter(date=from_date,
                    amount__range=(amount_min, amount_max)).values_list('settlement__room__hotel__pk',
                    flat=True).distinct()
            else:
                hotels_with_amount = PlacePrice.objects.filter(date=now(),
                    amount__range=(amount_min, amount_max)).values_list('settlement__room__hotel__pk',
                    flat=True).distinct()
            searched = searched.filter(pk__in=hotels_with_amount, work_on_request=False)
        if options:
            for option in options:
                searched = searched.filter(option=option)
        if stars:
            searched = searched.filter(starcount__in=stars)
        searched = searched.order_by('starcount')
        results = []
        for hotel in searched:
            answer = {'name': hotel.get_name, 'latitude': hotel.latitude, 'url': hotel.get_absolute_url(),
                      'address': hotel.address, 'id': hotel.pk, 'starcount': hotel.starcount,
                      'img': make_thumbnail(hotel.main_image, width=113, height=75, aspect=1),
                      'longitude': hotel.longitude, 'starcount_name': hotel.get_starcount_display(),
                      'amount': str(int(hotel.current_amount))}

            results.append(answer)
        payload = {'success': True, 'hotels': results}
    except:
        payload = {'success': False}
    return ajax_answer_lazy(payload)
示例#37
0
def filter_hotels_on_map(request, hotels):
    try:
        searched = hotels
        f_date = request.POST.get('start_date') or None
        amount_min = request.POST.get('amount_min') or None
        amount_max = request.POST.get('amount_max') or None
        options = request.POST.getlist('options') or None
        stars = request.POST.getlist('stars') or None
        if amount_max and amount_min:
            if f_date:
                from_date = convert_to_date(f_date)
                hotels_with_amount = PlacePrice.objects.filter(date=from_date,
                    amount__range=(amount_min, amount_max)).values_list('settlement__room__hotel__pk',
                    flat=True).distinct()
            else:
                hotels_with_amount = PlacePrice.objects.filter(date=now(),
                    amount__range=(amount_min, amount_max)).values_list('settlement__room__hotel__pk',
                    flat=True).distinct()
            searched = searched.filter(pk__in=hotels_with_amount, work_on_request=False)
        if options:
            for option in options:
                searched = searched.filter(option=option)
        if stars:
            searched = searched.filter(starcount__in=stars)
        searched = searched.order_by('starcount')
        results = []
        for hotel in searched:
            answer = {'name': hotel.get_name, 'latitude': hotel.latitude, 'url': hotel.get_absolute_url(),
                      'address': hotel.address, 'id': hotel.pk, 'starcount': hotel.starcount,
                      'img': make_thumbnail(hotel.main_image, width=113, height=75, aspect=1),
                      'longitude': hotel.longitude, 'starcount_name': hotel.get_starcount_display(),
                      'amount': str(int(hotel.current_amount))}

            results.append(answer)
        payload = {'success': True, 'hotels': results}
    except:
        payload = {'success': False}
    return ajax_answer_lazy(payload)
示例#38
0
def file_uploader(request, **kwargs):
    uploader = AjaxUploader(filetype='image', upload_dir=setting('IMAGE_UPLOAD_DIR', 'images'),
                            size_limit=setting('IMAGE_UPLOAD_SIZE', 10485760))
    result = uploader.handle_upload(request)
    if result['success']:
        ctype = get_object_or_404(ContentType, id=int(kwargs['content_type']))
        object_id = int(kwargs['object_id'])
        obj = ctype.get_object_for_this_type(pk=object_id)
        try:
            remove_thumbnails(obj.img.path)
            remove_file(obj.img.path)
            obj.img.delete()
        except:
            pass
        obj.img = result['path']
        obj.save()
        try:
            addons = dict(tmb=make_thumbnail(obj.img.url, width=int(kwargs['width']), height=int(kwargs['height']),
                                             aspect=int(kwargs['aspect'])))
        except:
            addons = {}
        result.update(addons)
    return AjaxAnswer(result)
示例#39
0
def thumbnail(url, args=''):
    """ Returns thumbnail URL and create it if not already exists.

.. note:: requires PIL_,
    if PIL_ is not found or thumbnail can not be created returns original URL.

.. _PIL: http://www.pythonware.com/products/pil/

Usage::

    {{ url|thumbnail:"width=10,height=20" }}
    {{ url|thumbnail:"width=10" }}
    {{ url|thumbnail:"height=20" }}

Parameters:

width
    requested image width

height
    requested image height

Image is **proportionally** resized to dimension which is no greather than ``width x height``.

Thumbnail file is saved in the same location as the original image
and his name is constructed like this::

    %(dirname)s/%(basename)s_t[_w%(width)d][_h%(height)d].%(extension)s

or if only a width is requested (to be compatibile with admin interface)::

    %(dirname)s/%(basename)s_t%(width)d.%(extension)s

"""
    if url is None:
        return None
    kwargs = {}
    if args:
        if ',' not in args:
            # ensure at least one ','
            args += ','
        for arg in args.split(','):
            arg = arg.strip()
            if arg == '':
                continue
            kw, val = arg.split('=', 1)
            kw = kw.lower().encode('ascii')
            try:
                val = int(val)  # convert all ints
            except ValueError:
                raise TemplateSyntaxError, "thumbnail filter: argument %r is invalid integer (%r)" % (kw, val)
            kwargs[kw] = val

    if ('width' not in kwargs) and ('height' not in kwargs):
        raise TemplateSyntaxError, "thumbnail filter requires arguments (width and/or height)"

    ret = make_thumbnail(url, **kwargs)
    if ret is None:
        ret = url

    if not ret.startswith(settings.MEDIA_URL):
        ret = settings.MEDIA_URL + ret

    return ret