Beispiel #1
0
def display(request, cart=None, error_message='', default_view_tax=None):
    """Display the items in the cart."""

    if default_view_tax is None:
        default_view_tax = config_value('TAX', 'DEFAULT_VIEW_TAX')

    if not cart:
        cart = Cart.objects.from_request(request)

    if cart.numItems > 0:
        products = [item.product for item in cart.cartitem_set.all()]
        sale = find_best_auto_discount(products)
    else:
        sale = None

    satchmo_cart_view.send(cart,
                           cart=cart,
                           request=request)

    context = RequestContext(request, {
        'cart': cart,
        'error_message': error_message,
        'default_view_tax' : default_view_tax,
        'sale' : sale,
        })
    return render_to_response('shop/cart.html', context_instance=context)
Beispiel #2
0
 def __init__(self, request, paymentmodule, *args, **kwargs):
     super(SimplePayShipForm, self).__init__(*args, **kwargs)
     
     self.order = None
     self.orderpayment = None
     
     try:
         self.tempCart = Cart.objects.from_request(request)
         if self.tempCart.numItems > 0:
             products = [item.product for item in self.tempCart.cartitem_set.all()]
             sale = find_best_auto_discount(products)
             if sale:
                 self.fields['discount'].initial = sale.code
         
     except Cart.DoesNotExist:
         self.tempCart = None
         
     try:
         self.tempContact = Contact.objects.from_request(request)
     except Contact.DoesNotExist:
         self.tempContact = None
         
     if kwargs.has_key('default_view_tax'):
         default_view_tax = kwargs['default_view_tax']
     else:
         default_view_tax = config_value_safe('TAX', 'TAX_SHIPPING', False)
         
     shipping_choices, shipping_dict = _get_shipping_choices(request, paymentmodule, self.tempCart, self.tempContact, default_view_tax=default_view_tax)
     self.fields['shipping'].choices = shipping_choices
     self.shipping_dict = shipping_dict
     
     if not config_value('PAYMENT', 'USE_DISCOUNTS'):
         self.fields['discount'].widget = forms.HiddenInput()
     
     signals.payment_form_init.send(SimplePayShipForm, form=self)
Beispiel #3
0
def category_view(request, slug, parent_slugs='', template='product/category.html'):
    """Display the category, its child categories, and its products.

    Parameters:
     - slug: slug of category
     - parent_slugs: ignored    
    """
    try:
        category = Category.objects.get(slug=slug)
        products = list(category.active_products())
        sale = find_best_auto_discount(products)

    except Category.DoesNotExist:
        return bad_or_missing(request, _('The category you have requested does not exist.'))

    child_categories = category.get_all_children()

    ctx = {
        'category': category, 
        'child_categories': child_categories,
        'sale' : sale,
        'products' : products,
    }
    index_prerender.send(Product, request=request, context=ctx, category=category, object_list=products)
    return render_to_response(template, RequestContext(request, ctx))
Beispiel #4
0
def display(request, cart=None, error_message='', default_view_tax=None):
    """Display the items in the cart."""

    if default_view_tax is None:
        default_view_tax = config_value('TAX', 'DEFAULT_VIEW_TAX')

    if not cart:
        cart = Cart.objects.from_request(request)

    if cart.numItems > 0:
        products = [item.product for item in cart.cartitem_set.all()]
        sale = find_best_auto_discount(products)
    else:
        sale = None

    satchmo_cart_view.send(cart,
                           cart=cart,
                           request=request)

    context = {
        'cart': cart,
        'error_message': error_message,
        'default_view_tax' : default_view_tax,
        'sale' : sale,
        }
    return render(request, 'shop/cart.html', context)
Beispiel #5
0
def saleindex(request):
    """
       display all the sale products
    """
    template = 'sale/index.html'
    discounts = Discount.objects.filter(active = True, automatic = True)
    products = []
    if discounts.count() > 0:
        for discount in list(discounts):
            if discount.valid_products.count() > 0:
                for product in discount.valid_products.filter(productvariation__parent__isnull=True).all():
                    product.discountIsValid, product.discountValidMsg = discount.isValid()
                    products.append(product)
    cart = Cart.objects.from_request(request)

    if cart.numItems > 0:
        productsInCart = [item.product for item in cart.cartitem_set.all()]
        sale = find_best_auto_discount(productsInCart)
    else:
        sale = None
       
    ctx = {
           'products':products,
           'sale': sale
           }
    return render_to_response(template, context_instance=RequestContext(request, ctx))
Beispiel #6
0
def category_view(request,
                  slug,
                  parent_slugs='',
                  template='product/category.html'):
    """Display the category, its child categories, and its products.

    Parameters:
     - slug: slug of category
     - parent_slugs: ignored
    """
    try:
        category = Category.objects.get_by_site(slug=slug)
        products = list(category.active_products())
        sale = find_best_auto_discount(products)

    except Category.DoesNotExist:
        return bad_or_missing(
            request, _('The category you have requested does not exist.'))

    child_categories = category.get_all_children()

    ctx = {
        'category': category,
        'child_categories': child_categories,
        'sale': sale,
        'products': products,
    }
    index_prerender.send(Product,
                         request=request,
                         context=ctx,
                         category=category,
                         object_list=products)
    return render(request, template, ctx)
Beispiel #7
0
def get_product(request,
                product_slug=None,
                selected_options=(),
                default_view_tax=None):
    """Basic product view"""

    errors = [m for m in get_messages(request) if m.level == constants.ERROR]

    try:
        product = Product.objects.get_by_site(active=True, slug=product_slug)
    except Product.DoesNotExist:
        return bad_or_missing(
            request, _('The product you have requested does not exist.'))

    if default_view_tax is None:
        default_view_tax = config_value('TAX', 'DEFAULT_VIEW_TAX')

    subtype_names = product.get_subtypes()

    # Save product id for xheaders, in case we display a ConfigurableProduct
    product_id = product.id

    # Clone product object in order to have current product variations in context (extra_context)
    current_product = product

    if 'ProductVariation' in subtype_names:
        selected_options = product.productvariation.unique_option_ids
        #Display the ConfigurableProduct that this ProductVariation belongs to.
        product = product.productvariation.parent.product
        subtype_names = product.get_subtypes()

    best_discount = find_best_auto_discount(product)

    if errors:
        error_message = errors[0]
    else:
        error_message = None

    extra_context = {
        'product': product,
        'current_product': current_product,
        'default_view_tax': default_view_tax,
        'sale': best_discount,
        'error_message': error_message,
    }

    # Get the template context from the Product.
    extra_context = product.add_template_context(
        context=extra_context,
        request=request,
        selected_options=selected_options,
        default_view_tax=default_view_tax)

    template = find_product_template(product, producttypes=subtype_names)
    context = RequestContext(request, extra_context)

    response = http.HttpResponse(template.render(context))
    populate_xheaders(request, response, Product, product_id)
    return response
Beispiel #8
0
def _find_sale(cart):
    if cart.numItems > 0:
        products = [item.product for item in cart.cartitem_set.all()]
        sale = find_best_auto_discount(products)
    else:
        sale = None

    return sale
Beispiel #9
0
def _find_sale(cart):
    if cart.numItems > 0:
        products = [item.product for item in cart.cartitem_set.all()]
        sale = find_best_auto_discount(products)
    else:
        sale = None

    return sale
Beispiel #10
0
def get_product(request, product_slug=None, selected_options=(),
    default_view_tax=None):
    """Basic product view"""

    errors = [m for m in get_messages(request) if m.level == constants.ERROR]

    try:
        product = Product.objects.get_by_site(active=True, slug=product_slug)
    except Product.DoesNotExist:
        return bad_or_missing(request, _('The product you have requested does not exist.'))

    if default_view_tax is None:
        default_view_tax = config_value('TAX', 'DEFAULT_VIEW_TAX')

    subtype_names = product.get_subtypes()

    # Save product id for xheaders, in case we display a ConfigurableProduct
    product_id = product.id

    # Clone product object in order to have current product variations in context (extra_context)
    current_product = product

    if 'ProductVariation' in subtype_names:
        selected_options = product.productvariation.unique_option_ids
        #Display the ConfigurableProduct that this ProductVariation belongs to.
        product = product.productvariation.parent.product
        subtype_names = product.get_subtypes()

    best_discount = find_best_auto_discount(product)

    if errors:
        error_message = errors[0]
    else:
        error_message = None

    extra_context = {
        'product': product,
        'current_product' : current_product,
        'default_view_tax': default_view_tax,
        'sale': best_discount,
        'error_message' : error_message,
    }

    # Get the template context from the Product.
    extra_context = product.add_template_context(context=extra_context,
        request=request, selected_options=selected_options,
        default_view_tax=default_view_tax)

    template = find_product_template(product, producttypes=subtype_names)
    context = RequestContext(request, extra_context)

    response = http.HttpResponse(template.render(context))
    try:
        from django.core.xheaders import populate_xheaders
        populate_xheaders(request, response, Product, product_id)
    except ImportError:
        pass
    return response
Beispiel #11
0
def home(request, template="shop/index.html"):
    # Display the category, its child categories, and its products.
    from localsite.models import Designer
    from product.models import Category
    from product.models import Product
    designer  = Designer.objects.filter(featured=True, active=True)

    if designer.count > 0:
        designer = designer[0]

    featuredCatIds = [1,2,3]
    featuredCats = []
    for id in featuredCatIds:
        if len(Category.objects.filter(id=id)):
            featuredCats.append(Category.objects.get(id=id))
#    featured = display_featured()
    class FeaturedCat:
        def __init__(self,name='',list =[]):
            self.name = name
            self.list = list
    featuredCatsCls = []
    if len(featuredCats):
        for f in featuredCats:
            childCats = f.get_all_children()
            pList = []
            if len(childCats):
                for cc in childCats:
                    pListincc = Product.objects.filter(category = cc,featured = True, active = True)
                    if pListincc.count():
                        pList.extend(list(pListincc))
            if len(pList):
                fCls = FeaturedCat(name = f.name,list = pList)
                featuredCatsCls.append(fCls)
    from localsite.models import PreOrderProduct
    featured_preorder_products_list = []
    featured_preorder_preOrderProducts_list = PreOrderProduct.objects.filter(featured = True)
    if featured_preorder_preOrderProducts_list.count():
        for f in list(featured_preorder_preOrderProducts_list):
            featured_preorder_products_list.append(f.product)
    cart = Cart.objects.from_request(request)

    if cart.numItems > 0:
        productsInCart = [item.product for item in cart.cartitem_set.all()]
        sale = find_best_auto_discount(productsInCart)
    else:
        sale = None
       
    ctx = RequestContext(request, {
        'featured_preorder_products_list' : featured_preorder_products_list,
        'featured_cats': featuredCatsCls,
        'designer' : designer,
        'sale': sale,
        'bodyid':'homepage'
    })
    
    return render_to_response(template, context_instance=ctx)
    
Beispiel #12
0
def untaxed_sale_price(product):
    """Returns the product unit price with the best auto discount applied."""
    discount = find_best_auto_discount(product)
    price = product.unit_price

    if discount and discount.valid_for_product(product):
        price = calc_discounted_by_percentage(price, discount.percentage)

    return price
Beispiel #13
0
def untaxed_sale_price(product):
    """Returns the product unit price with the best auto discount applied."""
    discount = find_best_auto_discount(product)
    price = product.unit_price
        
    if discount and discount.valid_for_product(cartitem.product):
        price = calc_discounted_by_percentage(price, disc.percentage)
    
    return price
Beispiel #14
0
 def get_context_data(self, **kwargs):
     context = super(DisplayView, self).get_context_data(**kwargs)
     if self.object.numItems > 0:
         products = [item.product for item in self.object.cartitem_set.all()]
         context['sale'] = find_best_auto_discount(products)
     context['error_message'] = self.get_error_message()
     context['default_view_tax'] = self.get_default_view_tax()
     satchmo_cart_view.send(self.object, cart=self.object, request=self.request)
     return context
Beispiel #15
0
def category_view_kamel(request,
                        slug,
                        parent_slugs='',
                        template='product/category.html'):
    """Display the category, its child categories, and its products.

    Parameters:
     - slug: slug of category
     - parent_slugs: ignored
    """
    if request.method == "GET":
        currpage = request.GET.get('page', 1)
        town = request.GET.get('town')
    else:
        currpage = 1
        town = 'Gdansk'

    is_paged = False
    page = None

    try:
        category = Category.objects.get_by_site(slug=slug)
        products = list(category.active_products())
        sale = find_best_auto_discount(products)
        count = config_value('PRODUCT', 'NUM_PAGINATED')
        paginator = Paginator(products, count)
        try:
            paginator.validate_number(currpage)
        except EmptyPage:
            return bad_or_missing(request, _("Invalid page number"))
        is_paged = paginator.num_pages > 1
        page = paginator.page(currpage)

    except Category.DoesNotExist:
        return bad_or_missing(
            request, _('The category you have requested does not exist.'))

    child_categories = category.get_all_children()

    ctx = {
        'category': category,
        'child_categories': child_categories,
        'sale': sale,
        'town': town,
        'products': page.object_list,
        'is_paginated': is_paged,
        'page_obj': page,
        'paginator': paginator
    }
    index_prerender.send(Product,
                         request=request,
                         context=ctx,
                         category=category,
                         object_list=products)
    return render_to_response(template,
                              context_instance=RequestContext(request, ctx))
Beispiel #16
0
    def get_context_data(self, **kwargs):
        context = super(CategoryView, self).get_context_data(**kwargs)
        context['category'] = self.category
        context['child_categories'] = self.category.get_all_children()
        context['sale'] = find_best_auto_discount(self.products)
        context['parent_slugs'] = self.kwargs['parent_slugs']

        index_prerender.send(Product, request=self.request, context=context,
                             category=self.category, object_list=self.products)
        return context
Beispiel #17
0
 def get_context_data(self, **kwargs):
     context = super(BrandDetailView, self).get_context_data(**kwargs)
     products = list(self.object.active_products())
     context['products'] = products
     context['sale'] = find_best_auto_discount(products)
     signals.index_prerender.send(self.model,
                                  request=self.request,
                                  context=context,
                                  brand=self.object,
                                  object_list=products)
     return context
    def testAutomaticDiscountedOrder(self):
        """Order with valid discount"""
        start = datetime.date(2011, 1, 1)
        end = datetime.date(2016, 1, 1)
        self.discount = make_test_discount(description="New Sale",
                                           code="BUYME",
                                           amount="5.00",
                                           allowedUses=100,
                                           numUses=0,
                                           minOrder=0,
                                           active=True,
                                           automatic=True,
                                           startDate=start,
                                           endDate=end,
                                           shipping='NONE',
                                           site=self.site)

        v = self.discount.isValid()
        self.assert_(v[0])
        self.assertEqual(v[1], u'Valid.')

        order = make_test_order(self.IT, '')
        # BBB: discount_code is required! If you don't specify discount_code,
        # none (existing valid) discount will bi applied to current order
        order.discount_code = "BUYME"
        order.save()

        product = order.orderitem_set.all()[0].product
        best_discount = find_best_auto_discount(product)
        self.assertEqual(best_discount, self.discount)

        order.recalculate_total(save=False)
        price = order.total
        subtotal = order.sub_total
        tax = order.tax

        self.assertEqual(subtotal, Decimal('50.00'))
        self.assertEqual(tax, Decimal('12.60'))
        # 50 - 5 (discount) + 10 shipping + 12.6 (21% on 60) tax
        self.assertEqual(price, Decimal('67.60'))

        taxes = order.taxes.all()
        self.assertEqual(2, len(taxes))
        t1 = taxes[0]
        t2 = taxes[1]
        self.assert_('Shipping' in (t1.description, t2.description))
        if t1.description == 'Shipping':
            tship = t1
            tmain = t2
        else:
            tship = t2
            tmain = t1
        self.assertEqual(tmain.tax, Decimal('10.50'))
        self.assertEqual(tship.tax, Decimal('2.10'))
Beispiel #19
0
 def get_context_data(self, **kwargs):
     context = super(CategoryView, self).get_context_data(**kwargs)
     products = list(self.object.active_products())
     context['child_categories'] = self.object.get_all_children()
     context['sale'] = find_best_auto_discount(products)
     context['products'] = products
     index_prerender.send(Product,
                          request=self.request,
                          context=context,
                          category=self.object,
                          object_list=products)
     return context
    def testMultipleDiscountedOrder(self):
        """Order with valid discount"""
        start = datetime.date(2011, 1, 1)
        end = datetime.date(2016, 1, 1)
        discount1 = make_test_discount(description="New Sale 1", code="BUYME1", amount="5.00", allowedUses=100,
            numUses=0, minOrder=0, active=True, automatic=True, startDate=start, endDate=end, shipping='NONE', site=self.site)
        
        discount2 = make_test_discount(description="New Sale 2", code="BUYME2", amount="1.00", allowedUses=100,
            numUses=0, minOrder=0, active=True, automatic=True, startDate=start, endDate=end, shipping='NONE', site=self.site)
        
        v = discount1.isValid()
        self.assert_(v[0])
        self.assertEqual(v[1], u'Valid.')
        
        v = discount2.isValid()
        self.assert_(v[0])
        self.assertEqual(v[1], u'Valid.')
        order = make_test_order(self.IT, '')
        # BBB: discount_code is required! If you don't specify discount_code,
        # none (existing valid) discount will bi applied to current order
        order.discount_code = "BUYME2"
        order.save()
        
        product = order.orderitem_set.all()[0].product
        best_discount = find_best_auto_discount(product)
        self.assertEqual(best_discount, discount1)
        
        order.recalculate_total(save=False)
        price = order.total
        subtotal = order.sub_total
        tax = order.tax

        self.assertEqual(subtotal, Decimal('50.00'))
        self.assertEqual(tax, Decimal('12.60'))
        # 50 - 1 (discount 2) + 10 shipping + 12.6 (21% on 60) tax
        self.assertEqual(price, Decimal('71.60'))

        taxes = order.taxes.all()
        self.assertEqual(2, len(taxes))
        t1 = taxes[0]
        t2 = taxes[1]
        self.assert_('Shipping' in (t1.description, t2.description))
        if t1.description == 'Shipping':
            tship = t1
            tmain = t2
        else:
            tship = t2
            tmain = t1
        self.assertEqual(tmain.tax, Decimal('10.50'))
        self.assertEqual(tship.tax, Decimal('2.10'))
        
Beispiel #21
0
 def get_context_data(self, **kwargs):
     self.product = self.get_product_variation()
     default_view_tax = self.get_default_view_tax()
     context = super(ProductView, self).get_context_data(**kwargs)
     context['product'] = self.product
     context['sale'] = find_best_auto_discount(self.product)
     context['error_message'] = self.get_error_message()
     context['default_view_tax'] = default_view_tax
     context = self.product.add_template_context(
         context=context,
         request=self.request,
         selected_options=self.selected_options,
         default_view_tax=default_view_tax)
     return context
Beispiel #22
0
def category_view(request, slug, parent_slugs='', template='product/category.html'):
    """Display the category, its child categories, and its products.

    Parameters:
     - slug: slug of category
     - parent_slugs: ignored
    """

    if request.method == "GET":
        currpage = request.GET.get('page', 1)
    else:
        currpage = 1

    try:
        category = Category.objects.get_by_site(slug=slug)
        products = list(category.active_products())
        sale = find_best_auto_discount(products)

    except Category.DoesNotExist:
        return bad_or_missing(request, _('The category you have requested does not exist.'))

    child_categories = category.get_all_children()

    count = config_value('PRODUCT','NUM_PAGINATED')

    paginator = Paginator(products, count)

    try:
        paginator.validate_number(currpage)
    except InvalidPage:
        return bad_or_missing(request, _("Invalid page number"))

    page = paginator.page(currpage)
    min_in_page = (count * (page.number - 1) + 1)
    max_in_page = min_in_page + (len(page.object_list) - 1)

    ctx = {
        'category': category,
        'child_categories': child_categories,
        'sale': sale,
        'products': page.object_list,
        'page_obj': page,
        'paginator': paginator,
        'min_in_page': min_in_page,
        'max_in_page': max_in_page
    }

    index_prerender.send(Product, request=request, context=ctx, category=category, object_list=products)
    return render_to_response(template, context_instance=RequestContext(request, ctx))
Beispiel #23
0
def pay_ship_render_form(request, form, template, payment_module, cart):
    template = lookup_template(payment_module, template)
    
    if cart.numItems > 0:
        products = [item.product for item in cart.cartitem_set.all()]
        sale = find_best_auto_discount(products)
    else:
        sale = None
        
    ctx = RequestContext(request, {
        'form': form,
        'sale' : sale,
        'PAYMENT_LIVE': payment_live(payment_module),
        })
    return render_to_response(template, ctx)
Beispiel #24
0
def brand_category_page(request, brandname, catname):
    try:
        cat = BrandCategory.objects.by_slug(brandname, catname)
        
    except Brand.DoesNotExist:
        raise Http404(_('Brand "%s" does not exist') % brandname)
        
    except BrandCategory.DoesNotExist:
        raise Http404(_('No category "%{category}s" in brand "%{brand}s"').format(category=catname, brand=brandname))
        
    products = list(cat.active_products())
    sale = find_best_auto_discount(products)
    
    ctx = RequestContext(request, {
        'brand' : cat,
        'sale' : sale,
    })
    return render_to_response('brand/view_brand.html', context_instance=ctx)
Beispiel #25
0
def offers(request, site=None):
    u"""Представление для списка товаров Яндекса"""
    site = get_object_or_404(YandexMarketSite, site=Site.objects.get_current())
    categories = Category.objects.filter(is_active=True, site=site)
    products = Product.objects.filter(active=True,
                site = site,
                category__in = categories,
                productvariation__parent__isnull=True)
    sale = find_best_auto_discount(list(products))
    ctx = RequestContext(request, {
            'date' : datetime.datetime.now().strftime('%Y-%m-%d %H:%M'),
            'categories' : categories,
            'offerproducts' : products,
            'site' : site,
            'sale' : sale,
        })
    return render_to_response('yandex_market/offers.html',
            context_instance=ctx)
Beispiel #26
0
def offers(request, site=None):
    u"""Представление для списка товаров Яндекса"""
    site = get_object_or_404(YandexMarketSite, site=Site.objects.get_current())
    categories = Category.objects.filter(is_active=True, site=site)
    products = Product.objects.filter(active=True,
                                      site=site,
                                      category__in=categories,
                                      productvariation__parent__isnull=True)
    sale = find_best_auto_discount(list(products))
    ctx = RequestContext(
        request, {
            'date': datetime.datetime.now().strftime('%Y-%m-%d %H:%M'),
            'categories': categories,
            'offerproducts': products,
            'site': site,
            'sale': sale,
        })
    return render_to_response('yandex_market/offers.html',
                              context_instance=ctx)
Beispiel #27
0
def category_index(request, template="product/category_index.html", root_only=True):
    """Display all categories.

    Parameters:
    - root_only: If true, then only show root categories.
    """
    cats = Category.objects.root_categories()
    cart = Cart.objects.from_request(request)

    if cart.numItems > 0:
        productsInCart = [item.product for item in cart.cartitem_set.all()]
        sale = find_best_auto_discount(productsInCart)
    else:
        sale = None
       
    ctx = {
        'categorylist' : cats,
        'sale': sale
    }
    return render_to_response(template, context_instance=RequestContext(request, ctx))
Beispiel #28
0
    def get_context_data(self, **kwargs):
        kwargs = super(CheckoutForm, self).get_context_data(**kwargs)
        shop = self.get_shop()
        if shop.in_country_only:
            only_country = shop.sales_country
        else:
            only_country = None

        payment_methods = kwargs['form'].fields['paymentmethod'].choices
        from product.utils import find_best_auto_discount
        if self.get_cart().numItems > 0:
            productsInCart = [item.product for item in self.get_cart().cartitem_set.all()]
            sale = find_best_auto_discount(productsInCart)
        else:
            sale = None
        kwargs.update({
            'country': only_country,'sale':sale,
            'paymentmethod_ct': len(payment_methods)
        })
        return kwargs
Beispiel #29
0
def brand_page(request, brandname):
    try:
        brand = Brand.objects.by_slug(brandname)
        
    except Brand.DoesNotExist:
        raise Http404(_('Brand "%s" does not exist') % brandname)

        
    products = list(brand.active_products())
    sale = find_best_auto_discount(products)

    ctx = {
        'brand' : brand,
        'products': products,
        'sale' : sale,
    }

    ctx = RequestContext(request, ctx)
    signals.index_prerender.send(BrandProduct, request=request, context=ctx, brand=brand, object_list=products)
    
    return render_to_response('brand/view_brand.html', ctx)
Beispiel #30
0
def brand_page(request, brandname):
    try:
        brand = Brand.objects.by_slug(brandname)
        
    except Brand.DoesNotExist:
        raise Http404(_('Brand "%s" does not exist') % brandname)

        
    products = list(brand.active_products())
    sale = find_best_auto_discount(products)

    ctx = {
        'brand' : brand,
        'products': products,
        'sale' : sale,
    }

    ctx = RequestContext(request, ctx)
    signals.index_prerender.send(BrandProduct, request=request, context=ctx, brand=brand, object_list=products)

    return render_to_response('brand/view_brand.html',
                              context_instance=ctx)
Beispiel #31
0
def get_product(request, product_slug=None, selected_options=(), 
    default_view_tax=NOTSET):
    """Basic product view"""
    
    errors = request.session.get('ERRORS', None)
    try:
        product = Product.objects.get_by_site(active=True, slug=product_slug)
    except Product.DoesNotExist:
        return bad_or_missing(request, _('The product you have requested does not exist.'))

    if default_view_tax == NOTSET:
        default_view_tax = config_value('TAX', 'DEFAULT_VIEW_TAX')

    subtype_names = product.get_subtypes()

    if 'ProductVariation' in subtype_names:
        selected_options = product.productvariation.unique_option_ids
        #Display the ConfigurableProduct that this ProductVariation belongs to.
        product = product.productvariation.parent.product
        subtype_names = product.get_subtypes()

    best_discount = find_best_auto_discount(product)
    
    extra_context = {
        'product': product,
        'default_view_tax': default_view_tax,
        'sale': best_discount,
        'error_message' : errors,
    }

    # Get the template context from the Product.
    extra_context = product.add_template_context(context=extra_context,
        request=request, selected_options=selected_options,
        default_view_tax=default_view_tax)

    template = find_product_template(product, producttypes=subtype_names)
    context = RequestContext(request, extra_context)
    return http.HttpResponse(template.render(context))
Beispiel #32
0
def get_discount(product):
    best_discount = find_best_auto_discount([product,])
    return best_discount
Beispiel #33
0
 def get_context_data(self, **kwargs):
     context = super(BrandCategoryDetailView,
                     self).get_context_data(**kwargs)
     products = list(self.object.active_products())
     context['sale'] = find_best_auto_discount(products)
     return context
Beispiel #34
0
def get_product(request, product_slug=None, selected_options=(), default_view_tax=None):
    """Basic product view"""

    errors = [m for m in get_messages(request) if m.level == constants.ERROR]

    try:
        product = Product.objects.get_by_site(active=True, slug=product_slug)
    except Product.DoesNotExist:
        return bad_or_missing(request, _('The product you have requested does not exist.'))

    if default_view_tax is None:
        default_view_tax = config_value('TAX', 'DEFAULT_VIEW_TAX')

    subtype_names = product.get_subtypes()

    in_stock = bool(product.items_in_stock)
    options_in_stock = []

    if 'ProductVariation' in subtype_names:
        selected_options = product.productvariation.unique_option_ids
        #Display the ConfigurableProduct that this ProductVariation belongs to.
        product = product.productvariation.parent.product

        for product_variation in product.configurableproduct.productvariation_set.all():
            if product_variation.product.items_in_stock:
                options_in_stock.append(product_variation.optionkey)

        in_stock = bool(options_in_stock)
        subtype_names = product.get_subtypes()

    elif 'ConfigurableProduct' in subtype_names:
        for product_variation in product.configurableproduct.productvariation_set.all():
            if product_variation.product.items_in_stock:
                options_in_stock.append(product_variation.optionkey)

        in_stock = bool(options_in_stock)

    best_discount = find_best_auto_discount(product)

    category = product.main_category
    products = list(category.active_products())

    # Save product id for xheaders, in case we display a ConfigurableProduct
    product_id = product.id

    # Clone product object in order to have current product variations in context (extra_context)
    current_product = product

    prev_prod = None
    next_prod = None

    cur_product_index = products.index(current_product)

    if cur_product_index != 0:
        prev_prod = products[cur_product_index - 1]

    if (cur_product_index + 1) < len(products):
        next_prod = products[cur_product_index + 1]

    if errors:
        error_message = errors[0]
    else:
        error_message = None

    extra_context = {
        'product': product,
        'current_product': current_product,
        'default_view_tax': default_view_tax,
        'sale': best_discount,
        'error_message': error_message,
        'next_prod': next_prod,
        'prev_prod': prev_prod,
        'cur_product_index': cur_product_index + 1,
        'count_products': len(products),
        'in_stock': in_stock,
        'options_in_stock': options_in_stock
    }

    # Get the template context from the Product.
    extra_context = product.add_template_context(context=extra_context,
        request=request, selected_options=selected_options,
        default_view_tax=default_view_tax)

    template = find_product_template(product, producttypes=subtype_names)
    context = RequestContext(request, extra_context)

    response = http.HttpResponse(template.render(context))
    populate_xheaders(request, response, Product, product_id)
    return response
Beispiel #35
0
def category_view(request, slug, parent_slugs='', template='product/category.html'):
    """Display the category, its child categories, and its products.

    Parameters:
     - slug: slug of category
     - parent_slugs: ignored
    """
    if request.GET.has_key('order_by') and request.GET['order_by']:
        orderBy= request.GET['order_by']
        if orderBy == 'price_inc':
            try:
                category =  Category.objects.get_by_site(slug=slug)
                #products = list(category.active_products())
                products = list(category.active_products())
                if len(products):
                    productsAndPrice = []
                    for p in products:
                        price = p.unit_price
                        productsAndPrice.append([price,p])
                    productsAndPrice.sort()
                    sortedProducts = []
                    for pp in productsAndPrice:
                        sortedProducts.append(pp[1])
                    products = sortedProducts
#                sale = find_best_auto_discount(products)
            except Category.DoesNotExist:
                return bad_or_missing(request, _('The category you have requested does not exist.'))
        
            child_categories = category.get_all_children()
            cart = Cart.objects.from_request(request)
        
            if cart.numItems > 0:
                productsInCart = [item.product for item in cart.cartitem_set.all()]
                sale = find_best_auto_discount(productsInCart)
            else:
                sale = None
               
            ctx = {
                'category': category,
                'child_categories': child_categories,
                'sale' : sale,
                'products' : products,
                'order_by' : 'price_inc'
            }
            index_prerender.send(Product, request=request, context=ctx, category=category, object_list=products)
            return render_to_response(template, context_instance=RequestContext(request, ctx))
        else:
            try:
                category =  Category.objects.get_by_site(slug=slug)
                #products = list(category.active_products())
                products = list(category.active_products())
                if len(products):
                    productsAndPrice = []
                    for p in products:
                        price = -p.unit_price
                        productsAndPrice.append([price,p])
                    productsAndPrice.sort()
                    sortedProducts = []
                    for pp in productsAndPrice:
                        sortedProducts.append(pp[1])
                    products = sortedProducts
#                sale = find_best_auto_discount(products)
                      
            except Category.DoesNotExist:
                return bad_or_missing(request, _('The category you have requested does not exist.'))
        
            child_categories = category.get_all_children()
            cart = Cart.objects.from_request(request)
        
            if cart.numItems > 0:
                productsInCart = [item.product for item in cart.cartitem_set.all()]
                sale = find_best_auto_discount(productsInCart)
            else:
                sale = None
            ctx = {
                'category': category,
                'child_categories': child_categories,
                'sale' : sale,
                'products' : products,
                'order_by' : 'price_dec'
            }
            index_prerender.send(Product, request=request, context=ctx, category=category, object_list=products)
            return render_to_response(template, context_instance=RequestContext(request, ctx))

    else:
        try:
            category =  Category.objects.get_by_site(slug=slug)
            #products = list(category.active_products())
            products = list(category.active_products())
    #        productsAndPrice = []
    #        for p in products:
    #            price = p.unit_price
    #            productsAndPrice.append([price,p])
    #        productsAndPrice.sort()
    #        sortedProducts = []
    #        for pp in productsAndPrice:
    #            sortedProducts.append(pp[1])
    #        products = sortedProducts
#            sale = find_best_auto_discount(products)

        except Category.DoesNotExist:
            return bad_or_missing(request, _('The category you have requested does not exist.'))
    
        child_categories = category.get_all_children()
        cart = Cart.objects.from_request(request)
    
        if cart.numItems > 0:
            productsInCart = [item.product for item in cart.cartitem_set.all()]
            sale = find_best_auto_discount(productsInCart)
        else:
            sale = None
        ctx = {
            'category': category,
            'child_categories': child_categories,
            'sale' : sale,
            'products' : products,
        }
        index_prerender.send(Product, request=request, context=ctx, category=category, object_list=products)
        return render_to_response(template, context_instance=RequestContext(request, ctx))