Example #1
0
def add(request, id=0):
    """Add an item to the cart."""
    #TODO: Error checking for invalid combos

    try:
        product = Product.objects.get(slug=request.POST['productname'])
        p_types = product.get_subtypes()
        details = []
        
        if 'ConfigurableProduct' in p_types:
            # This happens when productname cannot be updated by javascript.
            cp = product.configurableproduct
            chosenOptions = optionset_from_post(cp, request.POST)
            product = cp.get_product_from_options(chosenOptions)
                
        if 'CustomProduct' in p_types:
            for customfield in product.customproduct.custom_text_fields.all():
                details.append((customfield, request.POST["custom_%s" % customfield.slug]))
            
        template = find_product_template(product)
    except (Product.DoesNotExist, MultiValueDictKeyError):
        return bad_or_missing(request, _('The product you have requested does not exist.'))
        
    try:
        quantity = int(request.POST['quantity'])
    except ValueError:
        context = RequestContext(request, {
            'product': product,
            'error_message': _("Please enter a whole number.")})
        
        return HttpResponse(template.render(context))
        
    if quantity < 1:
        context = RequestContext(request, {
            'product': product,
            'error_message': _("Please enter a positive number.")})
        return HttpResponse(template.render(context))

    if request.session.get('cart'):
        cart = Cart.objects.get(id=request.session['cart'])
    else:
        cart = Cart()
        cart.save() # Give the cart an id
    
    cart.add_item(product, number_added=quantity, details=details)
    request.session['cart'] = cart.id

    url = urlresolvers.reverse('satchmo_cart')
    return HttpResponseRedirect(url)
Example #2
0
def settings(request):
    shop_config = Config.get_shop_config()
    cart = Cart.get_session_cart(request)

    all_categories = Category.objects.all()

    # handle secure requests
    media_url = site_settings.MEDIA_URL
    secure = request_is_secure(request)
    if secure:
        try:
            media_url = site_settings.MEDIA_SECURE_URL
        except AttributeError:
            media_url = media_url.replace("http://", "https://")

    return {
        "shop_base": site_settings.SHOP_BASE,
        "shop": shop_config,
        "shop_name": shop_config.store_name,
        "media_url": media_url,
        "cart_count": cart.numItems,
        "cart": cart,
        "categories": all_categories,
        "is_secure": secure,
        "request": request,
    }
Example #3
0
def settings(request):
    shop_config = Config.get_shop_config()
    cart = Cart.get_session_cart(request)

    all_categories = Category.objects.all()

    # handle secure requests
    media_url = site_settings.MEDIA_URL
    secure = request_is_secure(request)
    if secure:
        try:
            media_url = site_settings.MEDIA_SECURE_URL
        except AttributeError:
            media_url = media_url.replace('http://', 'https://')

    return {
        'shop_base': site_settings.SHOP_BASE,
        'shop': shop_config,
        'shop_name': shop_config.store_name,
        'media_url': media_url,
        'cart_count': cart.numItems,
        'cart': cart,
        'categories': all_categories,
        'is_secure': secure,
        'request': request,
    }
Example #4
0
def add_ajax(request, id=0, template="json.html"):
    data = {'errors': []}
    product = None
    productname = request.POST['productname']
    log.debug('CART_AJAX: slug=%s', productname)
    try:
        product = Product.objects.get(slug=request.POST['productname'])
        if 'ConfigurableProduct' in product.get_subtypes():
            log.debug('Got a configurable product, trying by option')
            # This happens when productname cannot be updated by javascript.
            cp = product.configurableproduct
            chosenOptions = optionset_from_post(cp, request.POST)
            product = cp.get_product_from_options(chosenOptions)
    except Product.DoesNotExist:
        log.warn("Could not find product: %s", productname)
        product = None

    if not product:
        data['errors'].append(
            ('product', _('The product you have requested does not exist.')))

    else:
        data['id'] = product.id
        data['name'] = product.name

        try:
            quantity = int(request.POST['quantity'])
            if quantity < 0:
                data['errors'].append(('quantity', _('Choose a quantity.')))

        except ValueError:
            data['errors'].append(('quantity', _('Choose a whole number.')))

    tempCart = Cart.get_session_cart(request, create=True)

    if not data['errors']:
        tempCart.add_item(product, number_added=quantity)
        request.session['cart'] = tempCart.id
        data['results'] = _('Success')
    else:
        data['results'] = _('Error')

    data['cart_count'] = tempCart.numItems

    encoded = JSONEncoder().encode(data)
    log.debug('CART AJAX: %s', data)

    return render_to_response(template, {'json': encoded})
Example #5
0
def add(request, id=0):
    """Add an item to the cart."""
    #TODO: Error checking for invalid combos

    try:
        product = Product.objects.get(slug=request.POST['productname'])
        p_types = product.get_subtypes()
        details = []

        if 'ConfigurableProduct' in p_types:
            # This happens when productname cannot be updated by javascript.
            cp = product.configurableproduct
            chosenOptions = optionset_from_post(cp, request.POST)
            product = cp.get_product_from_options(chosenOptions)

        if 'CustomProduct' in p_types:
            for customfield in product.customproduct.custom_text_fields.all():
                details.append((customfield,
                                request.POST["custom_%s" % customfield.slug]))

        template = find_product_template(product)
    except (Product.DoesNotExist, MultiValueDictKeyError):
        return bad_or_missing(
            request, _('The product you have requested does not exist.'))

    try:
        quantity = int(request.POST['quantity'])
    except ValueError:
        context = RequestContext(
            request, {
                'product': product,
                'error_message': _("Please enter a whole number.")
            })

        return HttpResponse(template.render(context))

    if quantity < 1:
        context = RequestContext(
            request, {
                'product': product,
                'error_message': _("Please enter a positive number.")
            })
        return HttpResponse(template.render(context))

    if request.session.get('cart'):
        cart = Cart.objects.get(id=request.session['cart'])
    else:
        cart = Cart()
        cart.save()  # Give the cart an id

    cart.add_item(product, number_added=quantity, details=details)
    request.session['cart'] = cart.id

    url = urlresolvers.reverse('satchmo_cart')
    return HttpResponseRedirect(url)
Example #6
0
def add_ajax(request, id=0, template="json.html"):
    data = {'errors': []}
    product = None
    productname = request.POST['productname'];
    log.debug('CART_AJAX: slug=%s', productname)
    try:
        product = Product.objects.get(slug=request.POST['productname'])
        if 'ConfigurableProduct' in product.get_subtypes():
            log.debug('Got a configurable product, trying by option')
            # This happens when productname cannot be updated by javascript.
            cp = product.configurableproduct
            chosenOptions = optionset_from_post(cp, request.POST)
            product = cp.get_product_from_options(chosenOptions)
    except Product.DoesNotExist:
        log.warn("Could not find product: %s", productname)
        product = None
        
    if not product:
        data['errors'].append(('product', _('The product you have requested does not exist.')))
    
    else:
        data['id'] = product.id
        data['name'] = product.name

        try:
            quantity = int(request.POST['quantity'])
            if quantity < 0:
                data['errors'].append(('quantity', _('Choose a quantity.')))

        except ValueError:
            data['errors'].append(('quantity', _('Choose a whole number.')))

    tempCart = Cart.get_session_cart(request, create=True)
    
    if not data['errors']:
        tempCart.add_item(product, number_added=quantity)
        request.session['cart'] = tempCart.id
        data['results'] = _('Success')
    else:
        data['results'] = _('Error')

    data['cart_count'] = tempCart.numItems
    
    encoded = JSONEncoder().encode(data)
    log.debug('CART AJAX: %s', data)

    return render_to_response(template, {'json' : encoded})
Example #7
0
    def test_line_cost(self):
        lb = Product.objects.get(slug__iexact="dj-rocks-l-bl")
        sb = Product.objects.get(slug__iexact="dj-rocks-s-b")

        cart = Cart()
        cart.save()
        cart.add_item(sb, 1)
        self.assertEqual(cart.numItems, 1)
        self.assertEqual(cart.total, Decimal("20.00"))

        cart.add_item(lb, 1)
        self.assertEqual(cart.numItems, 2)
        items = list(cart.cartitem_set.all())
        item1 = items[0]
        item2 = items[1]
        self.assertEqual(item1.unit_price, Decimal("20.00"))
        self.assertEqual(item2.unit_price, Decimal("23.00"))
        self.assertEqual(cart.total, Decimal("43.00"))
Example #8
0
    def testCartAddVerifyVeto(self):
        """Test that vetoes from `signals.satchmo_cart_add_verify` are caught and cause an error."""
        try:
            cart = Cart()
            cart.save()
            p = ProductFactory()
            cart.add_item(p, 1)
            TestOrderFactory()
            self.fail("Should have thrown a CartAddProhibited error")
        except CartAddProhibited:
            pass

        self.assertEqual(len(cart), 0)
Example #9
0
    def test_line_cost(self):
        lb = Product.objects.get(slug__iexact="dj-rocks-l-bl")
        sb = Product.objects.get(slug__iexact="dj-rocks-s-b")

        cart = Cart(site=Site.objects.get_current())
        cart.save()
        cart.add_item(sb, 1)
        self.assertEqual(cart.numItems, 1)
        self.assertEqual(cart.total, Decimal("20.00"))

        cart.add_item(lb, 1)
        self.assertEqual(cart.numItems, 2)
        items = list(cart.cartitem_set.all())
        item1 = items[0]
        item2 = items[1]
        self.assertEqual(item1.unit_price, Decimal("20.00"))
        self.assertEqual(item2.unit_price, Decimal("23.00"))
        self.assertEqual(cart.total, Decimal("43.00"))