コード例 #1
0
ファイル: products.py プロジェクト: aw1n/django-muecke
def remove_products(request, category_id):
    """Removes product (passed via request body) from category with passed id.
    """
    category = Category.objects.get(pk=category_id)

    for product_id in request.POST.keys():

        if product_id.startswith("page") or product_id.startswith("filter") or \
           product_id.startswith("keep-session") or product_id.startswith("action"):
            continue

        product = Product.objects.get(pk=product_id)
        product_changed.send(product)

        category.products.remove(product_id)

    category_changed.send(category)

    html = [[
        "#products-inline",
        products_inline(request, category_id, as_string=True)
    ]]

    result = simplejson.dumps(
        {
            "html": html,
            "message": _(u"Selected products have been removed from category.")
        },
        cls=LazyEncoder)

    return HttpResponse(result)
コード例 #2
0
def remove_products(request, manufacturer_id):
    """Removes product (passed via request body) from category with passed id.
    """
    manufacturer = Manufacturer.objects.get(pk=manufacturer_id)

    for product_id in request.POST.keys():
        if product_id.startswith("manufacturer_page") or product_id.startswith("manufacturer_filter") or \
           product_id.startswith("keep-session") or product_id.startswith("action"):
            continue

        product = Product.objects.get(pk=product_id)
        product.manufacturer = None
        product.save()
        product_changed.send(product)
    manufacturer_changed.send(manufacturer)

    html = [[
        "#products-inline",
        products_inline(request, manufacturer_id, as_string=True)
    ]]

    result = json.dumps(
        {
            "html":
            html,
            "message":
            _(u"Selected products are no longer assigned to manufacturer.")
        },
        cls=LazyEncoder)

    return HttpResponse(result, content_type='application/json')
コード例 #3
0
ファイル: accessories.py プロジェクト: zenith0/django-muecke
def add_accessories(request, product_id):
    """Adds passed accessories to product with passed id.
    """
    parent_product = Product.objects.get(pk=product_id)

    for temp_id in request.POST.keys():

        if temp_id.startswith("product") == False:
            continue

        temp_id = temp_id.split("-")[1]
        accessory = Product.objects.get(pk=temp_id)
        product_accessory = ProductAccessories(product=parent_product, accessory=accessory)
        product_accessory.save()

    _update_positions(parent_product)
    product_changed.send(parent_product)

    html = [["#accessories-inline", manage_accessories_inline(request, product_id, as_string=True)]]

    result = simplejson.dumps({
        "html": html,
        "message": _(u"Accessories have been added.")
    }, cls=LazyEncoder)

    return HttpResponse(result)
コード例 #4
0
ファイル: products.py プロジェクト: zenith0/django-muecke
def remove_products(request, category_id):
    """Removes product (passed via request body) from category with passed id.
    """
    category = Category.objects.get(pk=category_id)

    for product_id in request.POST.keys():

        if product_id.startswith("page") or product_id.startswith("filter") or \
           product_id.startswith("keep-session") or product_id.startswith("action"):
            continue

        product = Product.objects.get(pk=product_id)
        product_changed.send(product)

        category.products.remove(product_id)

    category_changed.send(category)

    html = [["#products-inline", products_inline(request, category_id, as_string=True)]]

    result = simplejson.dumps({
        "html": html,
        "message": _(u"Selected products have been removed from category.")
    }, cls=LazyEncoder)

    return HttpResponse(result)
コード例 #5
0
ファイル: products.py プロジェクト: zenith0/django-muecke
def add_products(request, manufacturer_id):
    """Adds products (passed via request body) to category with passed id.
    """
    manufacturer = Manufacturer.objects.get(pk=manufacturer_id)

    for product_id in request.POST.keys():
        if product_id.startswith("manufacturer_page") or product_id.startswith("manufacturer_filter") or \
           product_id.startswith("keep-session") or product_id.startswith("action"):
            continue

        try:
            product = Product.objects.get(pk=product_id)
            product.manufacturer = manufacturer
            product.save()
            product_changed.send(product)
        except Product.DoesNotExist:
            continue
    manufacturer_changed.send(manufacturer)

    html = [["#products-inline", products_inline(request, manufacturer_id, as_string=True)]]

    result = json.dumps({
        "html": html,
        "message": _(u"Selected products have been assigned to manufacturer.")
    }, cls=LazyEncoder)

    return HttpResponse(result, content_type='application/json')
コード例 #6
0
ファイル: accessories.py プロジェクト: aw1n/django-muecke
def add_accessories(request, product_id):
    """Adds passed accessories to product with passed id.
    """
    parent_product = Product.objects.get(pk=product_id)

    for temp_id in request.POST.keys():

        if temp_id.startswith("product") == False:
            continue

        temp_id = temp_id.split("-")[1]
        accessory = Product.objects.get(pk=temp_id)
        product_accessory = ProductAccessories(product=parent_product,
                                               accessory=accessory)
        product_accessory.save()

    _update_positions(parent_product)
    product_changed.send(parent_product)

    html = [[
        "#accessories-inline",
        manage_accessories_inline(request, product_id, as_string=True)
    ]]

    result = simplejson.dumps(
        {
            "html": html,
            "message": _(u"Accessories have been added.")
        },
        cls=LazyEncoder)

    return HttpResponse(result)
コード例 #7
0
ファイル: variants.py プロジェクト: aw1n/django-muecke
def edit_sub_type(request, product_id):
    """Edits the sub type of the variant with given product slug.
    """
    product = Product.objects.get(pk=product_id)

    form = DisplayTypeForm(data=request.POST)
    if form.is_valid():
        product.variants_display_type = request.POST.get(
            "variants_display_type")
        product.save()

    # Send a signal to update cache
    product_changed.send(product)

    html = (("#variants", manage_variants(request, product_id,
                                          as_string=True)), )

    result = simplejson.dumps(
        {
            "html": html,
            "message": _(u"Sup type has been saved."),
        },
        cls=LazyEncoder)

    return HttpResponse(result)
コード例 #8
0
def add_products(request, manufacturer_id):
    """Adds products (passed via request body) to category with passed id.
    """
    manufacturer = Manufacturer.objects.get(pk=manufacturer_id)

    for product_id in request.POST.keys():
        if product_id.startswith("manufacturer_page") or product_id.startswith("manufacturer_filter") or \
           product_id.startswith("keep-session") or product_id.startswith("action"):
            continue

        try:
            product = Product.objects.get(pk=product_id)
            product.manufacturer = manufacturer
            product.save()
            product_changed.send(product)
        except Product.DoesNotExist:
            continue
    manufacturer_changed.send(manufacturer)

    html = [[
        "#products-inline",
        products_inline(request, manufacturer_id, as_string=True)
    ]]

    result = json.dumps(
        {
            "html": html,
            "message":
            _(u"Selected products have been assigned to manufacturer.")
        },
        cls=LazyEncoder)

    return HttpResponse(result, content_type='application/json')
コード例 #9
0
ファイル: accessories.py プロジェクト: zenith0/django-muecke
def remove_accessories(request, product_id):
    """Removes passed accessories from product with passed id.
    """
    parent_product = Product.objects.get(pk=product_id)

    if request.POST.get("action") == "remove":
        for temp_id in request.POST.keys():

            if temp_id.startswith("accessory") == False:
                continue

            temp_id = temp_id.split("-")[1]
            accessory = Product.objects.get(pk=temp_id)
            product_accessory = ProductAccessories.objects.filter(product=parent_product, accessory=accessory)

            product_accessory.delete()

        _update_positions(parent_product)
        product_changed.send(parent_product)

        html = [["#accessories-inline", manage_accessories_inline(request, product_id, as_string=True)]]

        result = simplejson.dumps({
            "html": html,
            "message": _(u"Accessories have been removed.")
        }, cls=LazyEncoder)

    else:
        for temp_id in request.POST.keys():

            if temp_id.startswith("quantity") == False:
                continue

            temp_id = temp_id.split("-")[1]
            accessory = Product.objects.get(pk=temp_id)
            product_accessory = ProductAccessories.objects.get(product=parent_product, accessory=accessory)

            # Update quantity
            quantity = request.POST.get("quantity-%s" % temp_id)
            product_accessory.quantity = quantity

            # Update position
            position = request.POST.get("position-%s" % temp_id)
            product_accessory.position = position

            product_accessory.save()

            product_changed.send(product_accessory.product)

        _update_positions(parent_product)

        html = [["#accessories-inline", manage_accessories_inline(request, product_id, as_string=True)]]
        result = simplejson.dumps({
            "html": html,
            "message": _(u"Accessories have been updated.")
        }, cls=LazyEncoder)

    return HttpResponse(result)
コード例 #10
0
def update_images(request, product_id):
    """Saves/deletes images with given ids (passed by request body).
    """
    product = muecke_get_object_or_404(Product, pk=product_id)

    action = request.POST.get("action")
    if action == "delete":
        message = _(u"Images has been deleted.")
        for key in request.POST.keys():
            if key.startswith("delete-"):
                try:
                    id = key.split("-")[1]
                    image = Image.objects.get(pk=id).delete()
                except (IndexError, ObjectDoesNotExist):
                    pass

    elif action == "update":
        message = _(u"Images has been updated.")
        for key, value in request.POST.items():
            if key.startswith("title-"):
                id = key.split("-")[1]
                try:
                    image = Image.objects.get(pk=id)
                except ObjectDoesNotExist:
                    pass
                else:
                    image.title = value
                    image.save()

            elif key.startswith("position-"):
                try:
                    id = key.split("-")[1]
                    image = Image.objects.get(pk=id)
                except (IndexError, ObjectDoesNotExist):
                    pass
                else:
                    image.position = value
                    image.save()

    # Refresh positions
    for i, image in enumerate(product.images.all()):
        image.position = (i + 1) * 10
        image.save()

    product_changed.send(product, request=request)

    html = [["#images", manage_images(request, product_id, as_string=True)]]
    result = simplejson.dumps({
        "html": html,
        "message": message,
    },
                              cls=LazyEncoder)

    return HttpResponse(result)
コード例 #11
0
ファイル: images.py プロジェクト: zenith0/django-muecke
def update_images(request, product_id):
    """Saves/deletes images with given ids (passed by request body).
    """
    product = muecke_get_object_or_404(Product, pk=product_id)

    action = request.POST.get("action")
    if action == "delete":
        message = _(u"Images has been deleted.")
        for key in request.POST.keys():
            if key.startswith("delete-"):
                try:
                    id = key.split("-")[1]
                    image = Image.objects.get(pk=id).delete()
                except (IndexError, ObjectDoesNotExist):
                    pass

    elif action == "update":
        message = _(u"Images has been updated.")
        for key, value in request.POST.items():
            if key.startswith("title-"):
                id = key.split("-")[1]
                try:
                    image = Image.objects.get(pk=id)
                except ObjectDoesNotExist:
                    pass
                else:
                    image.title = value
                    image.save()

            elif key.startswith("position-"):
                try:
                    id = key.split("-")[1]
                    image = Image.objects.get(pk=id)
                except (IndexError, ObjectDoesNotExist):
                    pass
                else:
                    image.position = value
                    image.save()

    # Refresh positions
    for i, image in enumerate(product.images.all()):
        image.position = (i + 1) * 10
        image.save()

    product_changed.send(product, request=request)

    html = [["#images", manage_images(request, product_id, as_string=True)]]
    result = simplejson.dumps({
        "html": html,
        "message": message,
    }, cls=LazyEncoder)

    return HttpResponse(result)
コード例 #12
0
ファイル: attachments.py プロジェクト: zenith0/django-muecke
def add_attachment(request, product_id):
    """Adds an attachment to product with passed product_id.
    """
    product = muecke_get_object_or_404(Product, pk=product_id)
    if request.method == "POST":
        for file_content in request.FILES.getlist("file"):
            attachment = ProductAttachment(product=product, title=file_content.name)
            attachment.file.save(file_content.name, file_content, save=True)

    # Refresh positions
    for i, attachment in enumerate(product.attachments.all()):
        attachment.position = (i + 1) * 10
        attachment.save()

    product_changed.send(product, request=request)
    return manage_attachments(request, product_id)
コード例 #13
0
def add_attachment(request, product_id):
    """Adds an attachment to product with passed product_id.
    """
    product = muecke_get_object_or_404(Product, pk=product_id)
    if request.method == "POST":
        for file_content in request.FILES.getlist("file"):
            attachment = ProductAttachment(product=product,
                                           title=file_content.name)
            attachment.file.save(file_content.name, file_content, save=True)

    # Refresh positions
    for i, attachment in enumerate(product.attachments.all()):
        attachment.position = (i + 1) * 10
        attachment.save()

    product_changed.send(product, request=request)
    return manage_attachments(request, product_id)
コード例 #14
0
def move_image(request, id):
    """Moves the image with passed id up or down.

    **Parameters:**

        id
            The id of the image which should be edited.

    **Query String:**

        direction
            The direction in which the image should be moved. One of 0 (up)
            or 1 (down).

    **Permission:**

        edit (of the belonging content object)
    """
    image = Image.objects.get(pk=id)
    product = image.content

    direction = request.GET.get("direction", 0)

    if direction == "1":
        image.position += 15
    else:
        image.position -= 15
        if image.position < 0:
            image.position = 10

    image.save()

    # Refresh positions
    for i, image in enumerate(product.images.all()):
        image.position = (i + 1) * 10
        image.save()

    product_changed.send(product, request=request)

    html = [["#images", manage_images(request, product.id, as_string=True)]]

    result = simplejson.dumps({
        "html": html,
    }, cls=LazyEncoder)

    return HttpResponse(result)
コード例 #15
0
ファイル: images.py プロジェクト: zenith0/django-muecke
def move_image(request, id):
    """Moves the image with passed id up or down.

    **Parameters:**

        id
            The id of the image which should be edited.

    **Query String:**

        direction
            The direction in which the image should be moved. One of 0 (up)
            or 1 (down).

    **Permission:**

        edit (of the belonging content object)
    """
    image = Image.objects.get(pk=id)
    product = image.content

    direction = request.GET.get("direction", 0)

    if direction == "1":
        image.position += 15
    else:
        image.position -= 15
        if image.position < 0:
            image.position = 10

    image.save()

    # Refresh positions
    for i, image in enumerate(product.images.all()):
        image.position = (i + 1) * 10
        image.save()

    product_changed.send(product, request=request)

    html = [["#images", manage_images(request, product.id, as_string=True)]]

    result = simplejson.dumps({
         "html": html,
    }, cls=LazyEncoder)

    return HttpResponse(result)
コード例 #16
0
def update_attachments(request, product_id):
    """Saves/deletes attachments with given ids (passed by request body).
    """
    product = muecke_get_object_or_404(Product, pk=product_id)
    action = request.POST.get("action")
    message = _(u"Attachment has been updated.")

    if action == "delete":
        message = _(u"Attachment has been deleted.")
        for key in request.POST.keys():
            if key.startswith("delete-"):
                try:
                    id = key.split("-")[1]
                    attachment = ProductAttachment.objects.get(pk=id).delete()
                except (IndexError, ObjectDoesNotExist):
                    pass
    elif action == "update":
        message = _(u"Attachment has been updated.")
        for attachment in product.attachments.all():
            attachment.title = request.POST.get("title-%s" % attachment.id)
            attachment.position = request.POST.get("position-%s" %
                                                   attachment.id)
            attachment.description = request.POST.get("description-%s" %
                                                      attachment.id)
            attachment.save()

    # Refresh positions
    for i, attachment in enumerate(product.attachments.all()):
        attachment.position = (i + 1) * 10
        attachment.save()

    product_changed.send(product, request=request)

    html = [[
        "#attachments",
        manage_attachments(request, product_id, as_string=True)
    ]]
    result = simplejson.dumps({
        "html": html,
        "message": message,
    },
                              cls=LazyEncoder)

    return HttpResponse(result)
コード例 #17
0
ファイル: variants.py プロジェクト: zenith0/django-muecke
def update_category_variant(request, product_id):
    """
    Updates the category variant of the product with passed product_id.
    """
    product = Product.objects.get(pk=product_id)

    form = CategoryVariantForm(instance=product, data=request.POST)
    if form.is_valid():
        form.save()

    # Send a signal to update cache
    product_changed.send(product)

    html = (("#variants", manage_variants(request, product_id, as_string=True)),)

    result = simplejson.dumps({
        "html": html,
        "message": _(u"Category variant has been saved."),
    }, cls=LazyEncoder)

    return HttpResponse(result)
コード例 #18
0
ファイル: variants.py プロジェクト: zenith0/django-muecke
def edit_sub_type(request, product_id):
    """Edits the sub type of the variant with given product slug.
    """
    product = Product.objects.get(pk=product_id)

    form = DisplayTypeForm(data=request.POST)
    if form.is_valid():
        product.variants_display_type = request.POST.get("variants_display_type")
        product.save()

    # Send a signal to update cache
    product_changed.send(product)

    html = (("#variants", manage_variants(request, product_id, as_string=True)),)

    result = simplejson.dumps({
        "html": html,
        "message": _(u"Sup type has been saved."),
    }, cls=LazyEncoder)

    return HttpResponse(result)
コード例 #19
0
ファイル: attachments.py プロジェクト: zenith0/django-muecke
def update_attachments(request, product_id):
    """Saves/deletes attachments with given ids (passed by request body).
    """
    product = muecke_get_object_or_404(Product, pk=product_id)
    action = request.POST.get("action")
    message = _(u"Attachment has been updated.")

    if action == "delete":
        message = _(u"Attachment has been deleted.")
        for key in request.POST.keys():
            if key.startswith("delete-"):
                try:
                    id = key.split("-")[1]
                    attachment = ProductAttachment.objects.get(pk=id).delete()
                except (IndexError, ObjectDoesNotExist):
                    pass
    elif action == "update":
        message = _(u"Attachment has been updated.")
        for attachment in product.attachments.all():
            attachment.title = request.POST.get("title-%s" % attachment.id)
            attachment.position = request.POST.get("position-%s" % attachment.id)
            attachment.description = request.POST.get("description-%s" % attachment.id)
            attachment.save()

    # Refresh positions
    for i, attachment in enumerate(product.attachments.all()):
        attachment.position = (i + 1) * 10
        attachment.save()

    product_changed.send(product, request=request)

    html = [["#attachments", manage_attachments(request, product_id, as_string=True)]]
    result = simplejson.dumps({
        "html": html,
        "message": message,
    }, cls=LazyEncoder)

    return HttpResponse(result)
コード例 #20
0
ファイル: products.py プロジェクト: zenith0/django-muecke
def remove_products(request, manufacturer_id):
    """Removes product (passed via request body) from category with passed id.
    """
    manufacturer = Manufacturer.objects.get(pk=manufacturer_id)

    for product_id in request.POST.keys():
        if product_id.startswith("manufacturer_page") or product_id.startswith("manufacturer_filter") or \
           product_id.startswith("keep-session") or product_id.startswith("action"):
            continue

        product = Product.objects.get(pk=product_id)
        product.manufacturer = None
        product.save()
        product_changed.send(product)
    manufacturer_changed.send(manufacturer)

    html = [["#products-inline", products_inline(request, manufacturer_id, as_string=True)]]

    result = json.dumps({
        "html": html,
        "message": _(u"Selected products are no longer assigned to manufacturer.")
    }, cls=LazyEncoder)

    return HttpResponse(result, content_type='application/json')
コード例 #21
0
ファイル: variants.py プロジェクト: aw1n/django-muecke
def update_category_variant(request, product_id):
    """
    Updates the category variant of the product with passed product_id.
    """
    product = Product.objects.get(pk=product_id)

    form = CategoryVariantForm(instance=product, data=request.POST)
    if form.is_valid():
        form.save()

    # Send a signal to update cache
    product_changed.send(product)

    html = (("#variants", manage_variants(request, product_id,
                                          as_string=True)), )

    result = simplejson.dumps(
        {
            "html": html,
            "message": _(u"Category variant has been saved."),
        },
        cls=LazyEncoder)

    return HttpResponse(result)
コード例 #22
0
ファイル: accessories.py プロジェクト: aw1n/django-muecke
def remove_accessories(request, product_id):
    """Removes passed accessories from product with passed id.
    """
    parent_product = Product.objects.get(pk=product_id)

    if request.POST.get("action") == "remove":
        for temp_id in request.POST.keys():

            if temp_id.startswith("accessory") == False:
                continue

            temp_id = temp_id.split("-")[1]
            accessory = Product.objects.get(pk=temp_id)
            product_accessory = ProductAccessories.objects.filter(
                product=parent_product, accessory=accessory)

            product_accessory.delete()

        _update_positions(parent_product)
        product_changed.send(parent_product)

        html = [[
            "#accessories-inline",
            manage_accessories_inline(request, product_id, as_string=True)
        ]]

        result = simplejson.dumps(
            {
                "html": html,
                "message": _(u"Accessories have been removed.")
            },
            cls=LazyEncoder)

    else:
        for temp_id in request.POST.keys():

            if temp_id.startswith("quantity") == False:
                continue

            temp_id = temp_id.split("-")[1]
            accessory = Product.objects.get(pk=temp_id)
            product_accessory = ProductAccessories.objects.get(
                product=parent_product, accessory=accessory)

            # Update quantity
            quantity = request.POST.get("quantity-%s" % temp_id)
            product_accessory.quantity = quantity

            # Update position
            position = request.POST.get("position-%s" % temp_id)
            product_accessory.position = position

            product_accessory.save()

            product_changed.send(product_accessory.product)

        _update_positions(parent_product)

        html = [[
            "#accessories-inline",
            manage_accessories_inline(request, product_id, as_string=True)
        ]]
        result = simplejson.dumps(
            {
                "html": html,
                "message": _(u"Accessories have been updated.")
            },
            cls=LazyEncoder)

    return HttpResponse(result)
コード例 #23
0
    product = muecke_get_object_or_404(Product, pk=product_id)
    if request.method == "POST":
        for file_content in request.FILES.getlist("file"):
            image = Image(content=product, title=file_content.name)
            try:
                image.image.save(file_content.name, file_content, save=True)
            except Exception, e:
                logger.info("Upload image: %s %s" % (file_content.name, e))
                continue

    # Refresh positions
    for i, image in enumerate(product.images.all()):
        image.position = (i + 1) * 10
        image.save()

    product_changed.send(product, request=request)

    result = simplejson.dumps({
        "name": file_content.name,
        "type": "image/jpeg",
        "size": "123456789"
    })
    return HttpResponse(result)


@permission_required("core.manage_shop", login_url="/login/")
def update_images(request, product_id):
    """Saves/deletes images with given ids (passed by request body).
    """
    product = muecke_get_object_or_404(Product, pk=product_id)
コード例 #24
0
ファイル: images.py プロジェクト: zenith0/django-muecke
    product = muecke_get_object_or_404(Product, pk=product_id)
    if request.method == "POST":
        for file_content in request.FILES.getlist("file"):
            image = Image(content=product, title=file_content.name)
            try:
                image.image.save(file_content.name, file_content, save=True)
            except Exception, e:
                logger.info("Upload image: %s %s" % (file_content.name, e))
                continue

    # Refresh positions
    for i, image in enumerate(product.images.all()):
        image.position = (i + 1) * 10
        image.save()

    product_changed.send(product, request=request)

    result = simplejson.dumps({"name": file_content.name, "type": "image/jpeg", "size": "123456789"})
    return HttpResponse(result)


@permission_required("core.manage_shop", login_url="/login/")
def update_images(request, product_id):
    """Saves/deletes images with given ids (passed by request body).
    """
    product = muecke_get_object_or_404(Product, pk=product_id)

    action = request.POST.get("action")
    if action == "delete":
        message = _(u"Images has been deleted.")
        for key in request.POST.keys():
コード例 #25
0
ファイル: variants.py プロジェクト: zenith0/django-muecke
def update_variants(request, product_id):
    """Updates/Deletes variants with passed ids (via request body) dependent on
    given action (also via request body).
    """
    product = muecke_get_object_or_404(Product, pk=product_id)

    action = request.POST.get("action")
    if action == "delete":
        message = _(u"Variants have been deleted.")
        for key in request.POST.keys():
            if key.startswith("delete-"):
                try:
                    id = key.split("-")[1]
                    variant = Product.objects.get(pk=id)
                except (IndexError, ObjectDoesNotExist):
                    continue
                else:
                    if product.default_variant == variant:
                        product.default_variant = None
                        product.save()
                    variant.delete()
    elif action == "update":
        message = _(u"Variants have been saved.")
        for key, value in request.POST.items():
            if key.startswith("variant-"):
                id = key.split("-")[1]
                try:
                    variant = Product.objects.get(pk=id)
                except ObjectDoesNotExist:
                    continue
                else:
                    for name in ("slug", "sku", "price"):
                        value = request.POST.get("%s-%s" % (name, id))
                        if value != "":
                            setattr(variant, name, value)

                    # name
                    variant.name = request.POST.get("name-%s" % id)

                    # active
                    active = request.POST.get("active-%s" % id)
                    if active:
                        variant.active = True
                    else:
                        variant.active = False

                    # active attributes
                    for name in ("active_price", "active_sku", "active_name"):
                        value = request.POST.get("%s-%s" % (name, id))
                        if value:
                            setattr(variant, name, True)
                        else:
                            setattr(variant, name, False)

                    # position
                    position = request.POST.get("position-%s" % id)
                    try:
                        variant.variant_position = int(position)
                    except ValueError:
                        variant.variant_position = 10

                    # default variant
                    try:
                        product.default_variant_id = int(request.POST.get("default_variant"))
                    except TypeError:
                        pass
                    else:
                        product.save()

                variant.save()

            elif key.startswith("property"):
                # properties are marshalled as: property-variant_id|property_id
                temp = key.split("-")[1]
                variant_id, property_id = temp.split("|")
                variant = Product.objects.get(pk=variant_id)
                try:
                    ppv = variant.property_values.get(property=property_id, type=PROPERTY_VALUE_TYPE_VARIANT)
                except ProductPropertyValue.DoesNotExist:
                    # TODO: When creating new propertys (local or global), they are not copied onto existing variants.
                    continue
                ppv.value = value
                ppv.save()

    # Refresh variant positions
    for i, variant in enumerate(product.variants.order_by("variant_position")):
        variant.variant_position = (i + 1) * 10
        variant.save()

    # Send a signal to update cache
    product_changed.send(product)

    html = (
        ("#variants", manage_variants(request, product_id, as_string=True)),
        ("#selectable-products-inline", _selectable_products_inline(request, product)),
    )

    result = simplejson.dumps({
        "html": html,
        "message": message,
    }, cls=LazyEncoder)

    return HttpResponse(result)
コード例 #26
0
ファイル: variants.py プロジェクト: aw1n/django-muecke
def update_variants(request, product_id):
    """Updates/Deletes variants with passed ids (via request body) dependent on
    given action (also via request body).
    """
    product = muecke_get_object_or_404(Product, pk=product_id)

    action = request.POST.get("action")
    if action == "delete":
        message = _(u"Variants have been deleted.")
        for key in request.POST.keys():
            if key.startswith("delete-"):
                try:
                    id = key.split("-")[1]
                    variant = Product.objects.get(pk=id)
                except (IndexError, ObjectDoesNotExist):
                    continue
                else:
                    if product.default_variant == variant:
                        product.default_variant = None
                        product.save()
                    variant.delete()
    elif action == "update":
        message = _(u"Variants have been saved.")
        for key, value in request.POST.items():
            if key.startswith("variant-"):
                id = key.split("-")[1]
                try:
                    variant = Product.objects.get(pk=id)
                except ObjectDoesNotExist:
                    continue
                else:
                    for name in ("slug", "sku", "price"):
                        value = request.POST.get("%s-%s" % (name, id))
                        if value != "":
                            setattr(variant, name, value)

                    # name
                    variant.name = request.POST.get("name-%s" % id)

                    # active
                    active = request.POST.get("active-%s" % id)
                    if active:
                        variant.active = True
                    else:
                        variant.active = False

                    # active attributes
                    for name in ("active_price", "active_sku", "active_name"):
                        value = request.POST.get("%s-%s" % (name, id))
                        if value:
                            setattr(variant, name, True)
                        else:
                            setattr(variant, name, False)

                    # position
                    position = request.POST.get("position-%s" % id)
                    try:
                        variant.variant_position = int(position)
                    except ValueError:
                        variant.variant_position = 10

                    # default variant
                    try:
                        product.default_variant_id = int(
                            request.POST.get("default_variant"))
                    except TypeError:
                        pass
                    else:
                        product.save()

                variant.save()

            elif key.startswith("property"):
                # properties are marshalled as: property-variant_id|property_id
                temp = key.split("-")[1]
                variant_id, property_id = temp.split("|")
                variant = Product.objects.get(pk=variant_id)
                try:
                    ppv = variant.property_values.get(
                        property=property_id, type=PROPERTY_VALUE_TYPE_VARIANT)
                except ProductPropertyValue.DoesNotExist:
                    # TODO: When creating new propertys (local or global), they are not copied onto existing variants.
                    continue
                ppv.value = value
                ppv.save()

    # Refresh variant positions
    for i, variant in enumerate(product.variants.order_by("variant_position")):
        variant.variant_position = (i + 1) * 10
        variant.save()

    # Send a signal to update cache
    product_changed.send(product)

    html = (
        ("#variants", manage_variants(request, product_id, as_string=True)),
        ("#selectable-products-inline",
         _selectable_products_inline(request, product)),
    )

    result = simplejson.dumps({
        "html": html,
        "message": message,
    },
                              cls=LazyEncoder)

    return HttpResponse(result)