Example #1
0
    def test_product_image_deletion_does_not_delete_referenced_variation(self):
        try:
            from io import BytesIO
        except ImportError:
            from cStringIO import StringIO as BytesIO
        stream = BytesIO()

        from PIL import Image

        im = Image.new("RGB", (50, 50), "white")
        im.save(stream, "png")
        del im
        stream.seek(0)

        from django.core.files import File

        product = Product(title="Doodah", unit_price="2.99")
        product.save()

        image = ProductImage(product_id=product.id, file=File(stream))
        image.save()

        ProductVariation(unit_price="1.99", product_id=product.id, default=True, image=image).save()

        self.assertEqual(product.variations.count(), 1)
        image.delete()
        self.assertEqual(product.variations.count(), 1)
def main():
    breeds_list, links = parser_breeds()
    breeds_list = breeds_list[61:160]
    links = links[61:160]
    description = breeds_links_read(links)
    for i, breed in enumerate(breeds_list):
        print('Start downloading images for ' + breed)
        links = request_to_google_cse(API_KEY, breed, CUSTOM_SEARCH_ENGINE_ID,
                                      NUMBER_IMG_REQUIR)
        folder_single_breed_img = os.path.join(MEDIA_ROOT, 'uploads/product',
                                               breed)

        # create folder for each breed if it isn't exist
        if not os.path.exists(folder_single_breed_img):
            os.makedirs(folder_single_breed_img)

        new_dog_product = Product(available=True,
                                  title=breed,
                                  content=description[i])
        new_dog_product.save()
        variation = ProductVariation(product=new_dog_product,
                                     default=True,
                                     unit_price=choice(PRICE_CHOICES),
                                     sale_from=timezone.now())
        variation.save()
        for link in links['items']:
            try:
                img_resized = download_images_by_link(
                    breed, link['link'], IMG_WIDTH_REQUIR, IMG_HEIGHT_REQUIR,
                    os.path.join(MEDIA_ROOT, WATERMARK), WATERMARK_OPACITY,
                    MEDIA_ROOT)
                # create a new instance of ProductImage class and link it with Product class
                image = ProductImage(product=new_dog_product)

                # assign path to image to ProductImage instance
                image.file = img_resized
                image.save()
                print(img_resized + ' was downloaded')
            except HTTPError:
                print('HTTP Error 403: Forbidden. Link is not valid')
            except OSError:
                print('OSError.')

        # Set the first instance of ProductImage as default image for default variation
        new_dog_product.variations.set_default_images([])

        # Copy duplicate fields (``Priced`` fields) from the default variation to the product.
        new_dog_product.copy_default_variation()
Example #3
0
    def test_product_image_deletion_does_not_delete_referenced_variation(self):
        try:
            from io import BytesIO
        except ImportError:
            from cStringIO import StringIO as BytesIO
        stream = BytesIO()

        from PIL import Image
        im = Image.new("RGB", (50, 50), "white")
        im.save(stream, "png")
        del im
        stream.seek(0)

        from django.core.files import File

        product = Product(title="Doodah", unit_price="2.99")
        product.save()

        image = ProductImage(product_id=product.id, file=File(stream))
        image.save()

        ProductVariation(
            unit_price="1.99", product_id=product.id, default=True, image=image
        ).save()

        self.assertEqual(product.variations.count(), 1)
        image.delete()
        self.assertEqual(product.variations.count(), 1)
Example #4
0
def product(request, slug, template="shop/product.html"):
    """
    Display a product - convert the product variations to JSON as well as
    handling adding the product to either the cart or the wishlist.
    """
    published_products = Product.objects.published(for_user=request.user)
    product = get_object_or_404(published_products, slug=slug)
    fields = [f.name for f in ProductVariation.option_fields()]
    variations = product.variations.all()
    variations_json = simplejson.dumps([dict([(f, getattr(v, f))
                                        for f in fields + ["sku", "image_id"]])
                                        for v in variations])
    to_cart = (request.method == "POST" and
               request.POST.get("add_cart") is not None)

    save_product = (request.method == "POST" and
               request.POST.get("save_product") is not None)
    initial_data = {}
    if variations:
        initial_data = dict([(f, getattr(variations[0], f)) for f in fields])
    initial_data["quantity"] = 1

    quote = None
    if product.custom_product:
        quote_id = request.GET.get('quote_id')

        if quote_id:
            quote = get_object_or_404(Quote, pk=quote_id)
        add_product_form = AddCustomProductForm(request.POST or None, product=product,
                                      initial=initial_data, to_cart=to_cart, quote=quote)
    else:
        add_product_form = AddProductForm(request.POST or None, product=product,
                                      initial=initial_data, to_cart=to_cart)


    if request.method == "POST":

        if add_product_form.is_valid():
            if save_product:
                user_catagory = Category.objects.get(pk=15)

                new_product = product
                new_images = product.images.all()
                new_variations = variations

                for i in new_images:
                    i.pk = None
                    i.id = None
                    i.save()

                message = add_product_form.cleaned_data["message"]
                flat_message = message.replace('\n', ' ')

                new_product.pk = None
                new_product.id = None
                new_product.sku = None
                new_product.title = trunc(s=flat_message).title() + " Canvas Print"
                new_product.slug = None
                new_product.custom_product = False
                #new_product.available = False
                new_product.content = new_product.content +flat_message
                new_product.save()

                new_product.categories.add(user_catagory)
                new_product.images = new_images

                data_uri = add_product_form.cleaned_data["image_data"]
                img_str = re.search(r'base64,(.*)', data_uri).group(1)
                temp_img = img_str.decode('base64')
                image = ProductImage(file=ContentFile(temp_img, new_product.slug+'.png'), description = message, product=new_product)
                image.save()

                for v in new_variations:
                    v.pk = None
                    v.id = None
                    v.sku = None
                    v.image = image
                    v.save()

                new_product.variations = new_variations
                new_product.copy_default_variation()

                json = add_product_form.cleaned_data["json_data"]
                custom_product = CustomProduct(product = new_product, text = message, quote=quote, json=json)
                custom_product.save()

                return redirect("shop_product", slug=new_product.slug)

            elif to_cart:
                quantity = add_product_form.cleaned_data["quantity"]
                request.cart.add_item(add_product_form.variation, quantity)
                recalculate_cart(request)
                info(request, _("Item added to cart"))
                return redirect("shop_cart")
            else:
                skus = request.wishlist
                sku = add_product_form.variation.sku
                if sku not in skus:
                    skus.append(sku)
                info(request, _("Item added to wishlist"))
                response = redirect("shop_wishlist")
                set_cookie(response, "wishlist", ",".join(skus))
                return response
    context = {
        "product": product,
        "editable_obj": product,
        "images": product.images.all(),
        "variations": variations,
        "variations_json": variations_json,
        "has_available_variations": any([v.has_price() for v in variations]),
        "related_products": product.related_products.published(
                                                      for_user=request.user),
        "add_product_form": add_product_form
    }
    templates = [u"shop/%s.html" % unicode(product.slug), template]
    return render(request, templates, context)