コード例 #1
0
def product(request,
            slug,
            template="shop/product.html",
            form_class=AddProductForm,
            extra_context=None):
    """
    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 = 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_wishlist") is None)
    initial_data = {}
    if variations:
        initial_data = dict([(f, getattr(variations[0], f)) for f in fields])
    initial_data["quantity"] = 1
    add_product_form = form_class(request.POST or None,
                                  product=product,
                                  initial=initial_data,
                                  to_cart=to_cart)
    if request.method == "POST":
        if add_product_form.is_valid():
            if 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
    related = []
    if settings.SHOP_USE_RELATED_PRODUCTS:
        related = product.related_products.published(for_user=request.user)
    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": related,
        "add_product_form": add_product_form
    }
    context.update(extra_context or {})
    templates = [u"shop/%s.html" % str(product.slug), template]
    return TemplateResponse(request, templates, context)
コード例 #2
0
ファイル: views.py プロジェクト: LANtasy/website
    def update_formset(self):
        cart_formset = self.get_cart_formset()

        if self.request.cart.has_items() is False:
            warning(self.request, _("Cart is empty"))
        elif cart_formset.is_valid():
            cart_formset.save()
            recalculate_cart(self.request)
            billship_handler(self.request, None)
            tax_handler(self.request, None)
            info(self.request, _('Cart updated'))
        else:
            error(self.request, _('Invalid cart update'))

        order_form = self.get_order_form(checkout.CHECKOUT_STEP_FIRST)

        if order_form.is_valid():
            self.request.session['order'] = dict(order_form.cleaned_data)
        else:
            error(self.request, _('Invalid customer details'))

        context = self.get_context_data()
        context['cart_formset'] = self.get_cart_formset()
        context['order_form'] = order_form

        return context
コード例 #3
0
    def create(self, request, *args, **kwargs):
        sku, quantity = self.get_data(request.data)
        variation = self.get_variation(sku)

        if variation is None:
            return no_sku_error()

        kwargs = {"sku": variation.sku, "unit_price": variation.price()}
        in_cart = request.cart.items.filter(**kwargs).first()
        if in_cart is not None:
            if quantity <= 0:
                in_cart.delete()
            else:
                if variation.has_stock(quantity) is False:
                    quantity_available = variation.live_num_in_stock()
                    return not_enough_stock_error(quantity_available)

                in_cart.quantity = quantity
                in_cart.save()
        elif quantity > 0:
            request.cart.add_item(variation, quantity)
            recalculate_cart(request)

        able_to_purchase = variation is not None and variation.has_stock(
            quantity)
        not_enough_stock = variation is not None and variation.has_stock(
            quantity) is False

        if able_to_purchase:
            return Response(CartSerializer(request.cart).data)
        elif not_enough_stock:
            quantity_available = variation.live_num_in_stock()
            return not_enough_stock_error(quantity_available)
コード例 #4
0
def add_product(request, form_class=AddProductForm):
    """
    Display a product - handling adding the product the off canvas cart.
    """

    m = re.search(r"/product/(.*)/$", request.POST.get("slug"))
    slug = m.group(1)
    published_products = Product.objects.published(for_user=request.user)
    product = get_object_or_404(published_products, slug=slug)
    if request.is_ajax() and request.POST:
        to_cart = request.POST.get("add_cart")
        add_product_form = form_class(request.POST or None, product=product, to_cart=to_cart)
        if to_cart:
            if add_product_form.is_valid():
                quantity = add_product_form.cleaned_data["quantity"]
                request.cart.add_item(add_product_form.variation, quantity)
                info(request, _("Item added to cart"))
                recalculate_cart(request)
                return update_cart(request)
            else:
                error = add_product_form.non_field_errors()[0]
                return JsonResponse({'error': error})

    else:
        raise Http404
コード例 #5
0
    def create(self, request, *args, **kwargs):
        sku, quantity = self.get_data(request.data)
        variation = self.get_variation(sku)

        if variation is None:
            return no_sku_error()

        kwargs = {"sku": variation.sku, "unit_price": variation.price()}
        in_cart = request.cart.items.filter(**kwargs).first()
        if in_cart is not None:
            if quantity <= 0:
                in_cart.delete()
            else:
                if variation.has_stock(quantity) is False:
                    quantity_available = variation.live_num_in_stock()
                    return not_enough_stock_error(quantity_available)

                in_cart.quantity = quantity
                in_cart.save()
        elif quantity > 0:
            request.cart.add_item(variation, quantity)
            recalculate_cart(request)

        able_to_purchase = variation is not None and variation.has_stock(quantity)
        not_enough_stock = variation is not None and variation.has_stock(quantity) is False

        if able_to_purchase:
            return Response(CartSerializer(request.cart).data)
        elif not_enough_stock:
            quantity_available = variation.live_num_in_stock()
            return not_enough_stock_error(quantity_available)
コード例 #6
0
ファイル: member.py プロジェクト: hderaps/bccf
def membership(request, slug):
    slugs = [slug, 'membership/%s' % slug]
    the_category = None
    for categ in Category.objects.all():
        if categ.slug in slugs:
            the_category = categ
            break
    if not the_category:
        log.debug('Sorry, could not find membership types matching "%s"' % slug)
        return HttpResponseRedirect('/')

    if request.method == 'POST':
        variation_id = int(request.POST.get('variation_id'))
        variation = ProductVariation.objects.get(id=variation_id)
        request.cart.add_item(variation, 1)
        recalculate_cart(request)
        messages.success(request, "Your membership has been added to cart")
        request.session['aftercheckout'] = request.GET.get('next', '/')
        if request.cart.total_price():
            return redirect("shop_checkout")
        else:
            # For free membership, just fake the purchase process
            order = Order.objects.create()
            order.setup(request)
            order.complete(request)
            request.user.profile.set_membership_order(order)
            request.user.profile.save()
            checkout.send_order_email(request, order)
            return redirect("shop_complete")

    context = RequestContext(request, locals())
    return render_to_response('bccf/membership/membership.html', {}, context_instance=context)
コード例 #7
0
ファイル: views.py プロジェクト: davit-gh/flaunt
def get_carrier(request):
    if request.is_ajax() and request.method == 'POST':
        if not request.POST.get("free_shipping"):
            carrier = request.POST['carrier']
            shipping_type = request.POST['shipping_type']
            shipping_total = float(carrier.split()[3][1:])
            settings.use_editable()
            set_shipping(request, shipping_type, shipping_total)
            recalculate_cart(request)
        else:
            shipping_type = 'Regular Shipping'
            shipping_total = 0.0
            set_shipping(request, shipping_type, shipping_total)

        subtotal = float(request.cart.total_price())
        discount = float(request.session.get('discount_total', '0.00'))
        total = subtotal - discount + shipping_total
        total = "{0:.2f}".format(total)
        #resp = render_to_string('shop/cart.html', { 'request': request })
    return HttpResponse(json.dumps({
        'shipping_type': shipping_type,
        'shipping_total': shipping_total,
        'total_price': total,
        'discount': discount,
        'subtotal': subtotal
    }),
                        content_type='application/json')
コード例 #8
0
ファイル: events.py プロジェクト: hderaps/bccf
def event_payment(request, event_id):
    user = request.user
    event_reg = get_object_or_404(EventRegistration, ~Q(paid=True), event=event_id, user=user)
    event = event_reg.event
    variation = ProductVariation.objects.get(sku='EVENT-%s' % event.pk)
    request.cart.add_item(variation, 1)
    recalculate_cart(request)
    return redirect('shop/checkout')
コード例 #9
0
ファイル: views.py プロジェクト: raushanraj/cartridge
def product(request, slug, template="shop/product.html",
            form_class=AddProductForm, extra_context=None):
    """
    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 = 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_wishlist") is None)
    initial_data = {}
    if variations:
        initial_data = dict([(f, getattr(variations[0], f)) for f in fields])
    initial_data["quantity"] = 1
    add_product_form = form_class(request.POST or None, product=product,
                                  initial=initial_data, to_cart=to_cart)
    if request.method == "POST":
        if add_product_form.is_valid():
            if 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
    related = []
    if settings.SHOP_USE_RELATED_PRODUCTS:
        related = product.related_products.published(for_user=request.user)
    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": related,
        "add_product_form": add_product_form
    }
    context.update(extra_context or {})

    templates = [u"shop/%s.html" % str(product.slug), template]
    # Check for a template matching the page's content model.
    if getattr(product, 'content_model', None) is not None:
        templates.insert(0, u"shop/products/%s.html" % product.content_model)

    return TemplateResponse(request, templates, context)
コード例 #10
0
def cart(
    request,
    template="shop/cart.html",
    cart_formset_class=CartItemFormSet,
    discount_form_class=DiscountForm,
    extra_context=None,
):
    """
    Display cart and handle removing items from the cart.
    """
    cart_formset = cart_formset_class(instance=request.cart)
    discount_form = discount_form_class(request, request.POST or None)
    if request.method == "POST":
        valid = True
        if request.POST.get("update_cart"):
            valid = request.cart.has_items()
            if not valid:
                # Session timed out.
                info(request, _("Your cart has expired"))
            else:
                cart_formset = cart_formset_class(request.POST,
                                                  instance=request.cart)
                valid = cart_formset.is_valid()
                if valid:
                    cart_formset.save()
                    recalculate_cart(request)
                    info(request, _("Cart updated"))
                else:
                    # Reset the cart formset so that the cart
                    # always indicates the correct quantities.
                    # The user is shown their invalid quantity
                    # via the error message, which we need to
                    # copy over to the new formset here.
                    errors = cart_formset._errors
                    cart_formset = cart_formset_class(instance=request.cart)
                    cart_formset._errors = errors
        else:
            valid = discount_form.is_valid()
            if valid:
                discount_form.set_discount()
            # Potentially need to set shipping if a discount code
            # was previously entered with free shipping, and then
            # another was entered (replacing the old) without
            # free shipping, *and* the user has already progressed
            # to the final checkout step, which they'd go straight
            # to when returning to checkout, bypassing billing and
            # shipping details step where shipping is normally set.
            recalculate_cart(request)
        if valid:
            return redirect("shop_cart")
    context = {"cart_formset": cart_formset}
    context.update(extra_context or {})
    settings.clear_cache()
    if settings.SHOP_DISCOUNT_FIELD_IN_CART and DiscountCode.objects.active(
    ).exists():
        context["discount_form"] = discount_form
    return TemplateResponse(request, template, context)
コード例 #11
0
ファイル: views.py プロジェクト: davit-gh/flaunt
def get_discount_on_update(request, discount_form_class=DiscountForm):
	discount_form = discount_form_class(request, request.POST or None)
	valid = discount_form.is_valid()
        if valid:
		discount_form.set_discount()
		recalculate_cart(request)
		discount_total = float("{0:.2f}".format(float(request.session.get('discount_total','0.00'))))
	else:
		discount_total = 0
	
 	return discount_total
コード例 #12
0
ファイル: views.py プロジェクト: CoffenHu/cartridge
def cart(request, template="shop/cart.html",
         cart_formset_class=CartItemFormSet,
         discount_form_class=DiscountForm,
         extra_context=None):
    """
    Display cart and handle removing items from the cart.
    """
    cart_formset = cart_formset_class(instance=request.cart)
    discount_form = discount_form_class(request, request.POST or None)
    if request.method == "POST":
        valid = True
        if request.POST.get("update_cart"):
            valid = request.cart.has_items()
            if not valid:
                # Session timed out.
                info(request, _("Your cart has expired"))
            else:
                cart_formset = cart_formset_class(request.POST,
                                                  instance=request.cart)
                valid = cart_formset.is_valid()
                if valid:
                    cart_formset.save()
                    recalculate_cart(request)
                    info(request, _("Cart updated"))
                else:
                    # Reset the cart formset so that the cart
                    # always indicates the correct quantities.
                    # The user is shown their invalid quantity
                    # via the error message, which we need to
                    # copy over to the new formset here.
                    errors = cart_formset._errors
                    cart_formset = cart_formset_class(instance=request.cart)
                    cart_formset._errors = errors
        else:
            valid = discount_form.is_valid()
            if valid:
                discount_form.set_discount()
            # Potentially need to set shipping if a discount code
            # was previously entered with free shipping, and then
            # another was entered (replacing the old) without
            # free shipping, *and* the user has already progressed
            # to the final checkout step, which they'd go straight
            # to when returning to checkout, bypassing billing and
            # shipping details step where shipping is normally set.
            recalculate_cart(request)
        if valid:
            return redirect("shop_cart")
    context = {"cart_formset": cart_formset}
    context.update(extra_context or {})
    settings.use_editable()
    if (settings.SHOP_DISCOUNT_FIELD_IN_CART and
            DiscountCode.objects.active().exists()):
        context["discount_form"] = discount_form
    return TemplateResponse(request, template, context)
コード例 #13
0
ファイル: views.py プロジェクト: OscarGibson/vape-shop
def add_to_cart(request):

    if not request.method == 'POST':
        print('AAAA')
        return HttpResponse({}, status=400)

    print(request.POST)

    slug = request.POST.get('product-slug')

    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 = json.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_wishlist") is None)
    initial_data = {}
    if variations:
        initial_data = dict([(f, getattr(variations[0], f)) for f in fields])
    initial_data["quantity"] = 1
    add_product_form = AddProductForm(request.POST or None,
                                      product=product,
                                      initial=initial_data,
                                      to_cart=to_cart)
    if request.method == "POST":
        print(add_product_form)
        if add_product_form.is_valid():
            if to_cart:
                print('PRODUCT_FORM', add_product_form)
                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(requesadd_to_cartt, _("Item added to wishlist"))
                response = redirect("shop_wishlist")
                set_cookie(response, "wishlist", ",".join(skus))
                #return response
    data = {
        'total_price': format(request.cart.total_price(), '.2f'),
        'total_quantity': request.cart.total_quantity(),
        'wishlist': len(request.wishlist)
    }
    print(data)
    return HttpResponse(json.dumps(data), content_type="application/json")
コード例 #14
0
ファイル: views.py プロジェクト: davit-gh/flaunt
def get_discount_on_update(request, discount_form_class=DiscountForm):
    discount_form = discount_form_class(request, request.POST or None)
    valid = discount_form.is_valid()
    if valid:
        discount_form.set_discount()
        recalculate_cart(request)
        discount_total = float("{0:.2f}".format(
            float(request.session.get('discount_total', '0.00'))))
    else:
        discount_total = 0

    return discount_total
コード例 #15
0
ファイル: views.py プロジェクト: davit-gh/flaunt
def get_discount(request, discount_form_class=DiscountForm):
	if request.method == 'POST' and request.is_ajax():
		discount_form = discount_form_class(request, request.POST or None)
		ship_type = request.session.get('shipping_type','Shipping fee:')
		ship_total = request.session.get('shipping_total','0.00')
		valid = discount_form.is_valid()
        if valid:
        	discount_form.set_discount()
        	recalculate_cart(request)
        	discount_total = float(request.session.get('discount_total',0))
		return HttpResponse(json.dumps({'discount_total': "{0:.2f}".format(discount_total), 'cart_total':float(request.cart.total_price()),'shipping_total':ship_total, 'shipping_type':ship_type}), mimetype="application/json")
        else:
        	return HttpResponse(json.dumps(discount_form.errors), content_type="application/json")
コード例 #16
0
def wishlist(
    request,
    template="shop/wishlist.html",
    form_class=AddProductForm,
    extra_context=None,
):
    """
    Display the wishlist and handle removing items from the wishlist and
    adding them to the cart.
    """

    if not settings.SHOP_USE_WISHLIST:
        raise Http404

    skus = request.wishlist
    error = None
    if request.method == "POST":
        to_cart = request.POST.get("add_cart")
        add_product_form = form_class(request.POST or None, to_cart=to_cart)
        if to_cart:
            if add_product_form.is_valid():
                request.cart.add_item(add_product_form.variation, 1)
                recalculate_cart(request)
                message = _("Item added to cart")
                url = "shop_cart"
            else:
                error = list(add_product_form.errors.values())[0]
        else:
            message = _("Item removed from wishlist")
            url = "shop_wishlist"
        sku = request.POST.get("sku")
        if sku in skus:
            skus.remove(sku)
        if not error:
            info(request, message)
            response = redirect(url)
            set_cookie(response, "wishlist", ",".join(skus))
            return response

    # Remove skus from the cookie that no longer exist.
    published_products = Product.objects.published(for_user=request.user)
    f = {"product__in": published_products, "sku__in": skus}
    wishlist = ProductVariation.objects.filter(**f).select_related("product")
    wishlist = sorted(wishlist, key=lambda v: skus.index(v.sku))
    context = {"wishlist_items": wishlist, "error": error}
    context.update(extra_context or {})
    response = TemplateResponse(request, template, context)
    if len(wishlist) < len(skus):
        skus = [variation.sku for variation in wishlist]
        set_cookie(response, "wishlist", ",".join(skus))
    return response
コード例 #17
0
ファイル: views.py プロジェクト: jowolf/cartridge
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_wishlist") is None)
    initial_data = {}
    if variations:
        initial_data = dict([(f, getattr(variations[0], f)) for f in fields])
    initial_data["quantity"] = 1
    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 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)
コード例 #18
0
ファイル: views.py プロジェクト: CoffenHu/cartridge
def wishlist(request, template="shop/wishlist.html",
             form_class=AddProductForm, extra_context=None):
    """
    Display the wishlist and handle removing items from the wishlist and
    adding them to the cart.
    """

    if not settings.SHOP_USE_WISHLIST:
        raise Http404

    skus = request.wishlist
    error = None
    if request.method == "POST":
        to_cart = request.POST.get("add_cart")
        add_product_form = form_class(request.POST or None,
                                      to_cart=to_cart)
        if to_cart:
            if add_product_form.is_valid():
                request.cart.add_item(add_product_form.variation, 1)
                recalculate_cart(request)
                message = _("Item added to cart")
                url = "shop_cart"
            else:
                error = list(add_product_form.errors.values())[0]
        else:
            message = _("Item removed from wishlist")
            url = "shop_wishlist"
        sku = request.POST.get("sku")
        if sku in skus:
            skus.remove(sku)
        if not error:
            info(request, message)
            response = redirect(url)
            set_cookie(response, "wishlist", ",".join(skus))
            return response

    # Remove skus from the cookie that no longer exist.
    published_products = Product.objects.published(for_user=request.user)
    f = {"product__in": published_products, "sku__in": skus}
    wishlist = ProductVariation.objects.filter(**f).select_related("product")
    wishlist = sorted(wishlist, key=lambda v: skus.index(v.sku))
    context = {"wishlist_items": wishlist, "error": error}
    context.update(extra_context or {})
    response = TemplateResponse(request, template, context)
    if len(wishlist) < len(skus):
        skus = [variation.sku for variation in wishlist]
        set_cookie(response, "wishlist", ",".join(skus))
    return response
コード例 #19
0
ファイル: accounts.py プロジェクト: hderaps/bccf
def register_event(request):
    """
    Registers users to the event, registerer must complete registration using checkout if
    the event is not free
    """
    from cartridge.shop.utils import recalculate_cart
    from bccf.models import Event, EventRegistration
    
    member_ids = request.session['register_selected_members']
    event_id = request.session['register_selected_event']
    response = redirect(reverse('update'))
    message = 'Users registered successfully.'

    event = Event.objects.get(id=event_id)
    seats = len(EventRegistration.objects.filter(event=event)) + len(member_ids)
    
    if event.max_seats < seats: # Not everyone will fit
        error(request, 'There is not enough space in the event for your members.')
        return response
    
    if event.event_product: # If paid event, add event to cart
        variation = ProductVariation.objects.get(sku='EVENT-%s' % event.pk)
        request.cart.add_item(variation, len(member_ids))
        recalculate_cart(request)
        response = redirect('/shop/checkout')
        message = 'Users registered successfully. Please continue with the  checkout to complete registrations.'
        
        # Send event registration confirmation
        send_reminder("Event Registration Pending.", request.user, context={'event':event})
        
    else: # If not paid event, auto-register the members
        members = []        
        for member_id in member_ids:
            user = User.objects.get(id=member_id)
            members.append(user)
            EventRegistration.objects.create(user=user, event=event)
            send_reminder("Event Registration Complete.", user, context={'event': event})
          
        # Send event registration confirmation
        send_reminder("Event Registration Complete.", request.user, context={'event': event, 'members': members})

        # Delete session variables since the IDs have been registered
        del request.session['register_selected_members']
        del request.session['register_selected_event']   

    success(request, message)
    return response
コード例 #20
0
ファイル: events.py プロジェクト: hderaps/bccf
def signup(request, slug):
    if 'aftercheckout' in request.session:
        del request.session['aftercheckout']
    event = Event.objects.get(slug=slug)
    if request.method == 'POST':
        # Check if such registration already exists
        exists = False
        if not event.is_full():
           for existing in EventRegistration.objects.filter(user=request.user, event=event):
               messages.warning(request, 'You are already signed up to this event')
               exists = True
           if not exists:
               if event.event_product:
                   variation = ProductVariation.objects.get(sku='EVENT-%s' % event.pk)
                   request.cart.add_item(variation, 1)
                   recalculate_cart(request)
                   messages.success(request, 'To complete the registration, please go through the checkout.')
                   
                   # Send event registration confirmation
                   send_reminder("Event Registration Pending.", request.user, context={'event':event})
                   
               else:
                   registration = EventRegistration.objects.create(user=request.user, event=event)
                   
                   # Send event registration confirmation
                   send_reminder("Event Registration Complete.", request.user, context={'event':event})
                   
                   messages.success(request, 'Thank you! You signed up to the event successfully.')              
           if event.max_seats == len(EventRegistration.objects.filter(event=event)):
               event.full = True
               event.save()

               # Send event registration for provider
               attendees = EventRegistration.objects.filter(event=event)
               send_reminder("Event is now full", event.provider, context={'event':event, 'attendees':attendees})
             
           # Send event registration for provider
           send_reminder("A user registered for your event", event.provider, context={'event':event, 'attendee':request.user})
             
        else:
            messages.warning(request, 'The event is full.')
            
        return HttpResponseRedirect(event.get_absolute_url())
    context = RequestContext(request, locals())
    return render_to_response('bccf/event_signup.html', {}, context_instance=context)
コード例 #21
0
    def create(self, request, *args, **kwargs):
        sku, quantity = self.get_data(request.data)
        variation = self.get_variation(sku)

        if variation is None:
            return no_sku_error()

        able_to_purchase = variation is not None and variation.has_stock(quantity)
        not_enough_stock = variation is not None and variation.has_stock(quantity) is False

        if able_to_purchase:
            request.cart.add_item(variation, quantity)
            recalculate_cart(request)

            return Response(CartSerializer(request.cart).data)
        elif not_enough_stock:
            quantity_available = variation.live_num_in_stock()
            return not_enough_stock_error(quantity_available)
コード例 #22
0
ファイル: accounts.py プロジェクト: hderaps/bccf
def signup(request):
    # Optional queries
    membership_type = request.GET.get('type', None)
    membership_level = request.GET.get('level', None)
    payment_frequency = request.GET.get('freq', None)
    
    form = f.CreateAccountForm(initial={'membership_type': membership_type,
        'membership_level': membership_level, 'payment_frequency': payment_frequency})
    
    if request.method == 'POST':
        form = f.CreateAccountForm(data=request.POST, files=request.FILES)
        if form.is_valid():
            response = redirect('update')
            if form.cleaned_data.get('membership_level') != 'A':
                """
                If SKU exists in the query string and the SKU fits with the membership type, 
                add that product to the cart and redirect the user to the checkout
                """
                membership_type = form.cleaned_data.get('membership_type')[:3].upper()
                sku = '%s-%s-%s' % (membership_type, form.cleaned_data.get('membership_level'), form.cleaned_data.get('payment_frequency'))
                variation = ProductVariation.objects.get(sku=sku)
                request.cart.add_item(variation, 1)
                recalculate_cart(request)
                response = redirect('shop_checkout')
            form.save()
            
            subscribe(request, 'af67fb20e3', form.cleaned_data.get('email')) # Members list
            
            if form.cleaned_data.get('in_mailing_list'):
                subscribe(request, '8aebc01ca2', form.cleaned_data.get('email')) # News Letter
            
            new_user = authenticate(username=form.cleaned_data.get('username'), 
                                    password=form.cleaned_data.get('password1'))
            auth_login(request, new_user)
            
            # Send welcome message
            send_welcome(new_user)
            send_moderate("New user signed up.", context={'user': new_user})
            
            success(request, 'User created successfully! Welcome to the BCCF community %s' % form.instance.get_full_name())
            return response
    
    context = RequestContext(request, locals())
    return render_to_response('accounts/account_signup.html', {}, context)
コード例 #23
0
ファイル: views.py プロジェクト: hderaps/bccf
def cart(request, template="shop/cart.html"):
    """
    Display cart and handle removing items from the cart.
    """
    cart_formset = CartItemFormSet(instance=request.cart)
    discount_form = DiscountForm(request, request.POST or None)
    if request.method == "POST":
        valid = True
        if request.POST.get("update_cart"):
            valid = request.cart.has_items()
            if not valid:
                # Session timed out.
                info(request, _("Your cart has expired"))
            else:
                cart_formset = CartItemFormSet(request.POST,
                                               instance=request.cart)
                valid = cart_formset.is_valid()
                if valid:
                    cart_formset.save()
                    recalculate_cart(request)
                    info(request, _("Cart updated"))
                else:
                    # Reset the cart formset so that the cart
                    # always indicates the correct quantities.
                    # The user is shown their invalid quantity
                    # via the error message, which we need to
                    # copy over to the new formset here.
                    errors = cart_formset._errors
                    cart_formset = CartItemFormSet(instance=request.cart)
                    cart_formset._errors = errors
        else:
            valid = discount_form.is_valid()
            if valid:
                discount_form.set_discount()
        if valid:
            return redirect("shop_cart")
    context = {"cart_formset": cart_formset}
    settings.use_editable()
    no_discounts = not DiscountCode.objects.active().exists()
    discount_applied = "discount_code" in request.session
    discount_in_cart = settings.SHOP_DISCOUNT_FIELD_IN_CART
    if not no_discounts and not discount_applied and discount_in_cart:
        context["discount_form"] = discount_form
    return render(request, template, context)
コード例 #24
0
ファイル: views.py プロジェクト: LANtasy/website
    def formsets_valid(self, ticket_option_formset, product_formset):

        for form in itertools.chain(ticket_option_formset, product_formset):

            try:
                # If it's a ticket option
                variation = form.ticket_option
            except AttributeError:
                # If it's a product already
                variation = form.cleaned_data['id']
            quantity = form.cleaned_data['quantity']

            if quantity > 0:
                self.request.cart.add_item(variation=variation, quantity=quantity)

        tax_handler(self.request, None)
        recalculate_cart(self.request)

        return redirect('salesbro:portal_cart')
コード例 #25
0
    def create(self, request, *args, **kwargs):
        sku, quantity = self.get_data(request.data)
        variation = self.get_variation(sku)

        if variation is None:
            return no_sku_error()

        able_to_purchase = variation is not None and variation.has_stock(
            quantity)
        not_enough_stock = variation is not None and variation.has_stock(
            quantity) is False

        if able_to_purchase:
            request.cart.add_item(variation, quantity)
            recalculate_cart(request)

            return Response(CartSerializer(request.cart).data)
        elif not_enough_stock:
            quantity_available = variation.live_num_in_stock()
            return not_enough_stock_error(quantity_available)
コード例 #26
0
ファイル: views.py プロジェクト: Minhtvu/AirBespoke
def CustomSizeStep(request,
                   slug,
                   template="multiStepForm/customSizesStepForm.html"):

    form = CustomSizeStepForm(request.POST or None, request=request)
    if request.method == 'POST':
        if form.is_valid():
            sizeData = form.cleaned_data

            #add dimensions to request.session json
            #checking to see if dimensions are among json fields
            # for field in request.session.iteritems():
            #     print "data/fields in SUBMITTED DIMENSIONS: " + str(field)

            variation = ProductVariation.objects.get(
                product__sku=request.session['sku'])
            variation.height = sizeData['height']
            variation.weight = sizeData['weight']
            variation.neck_size = sizeData['neck_size']
            variation.chest_around = sizeData['chest_around']
            variation.sleeve_length = sizeData['sleeve_length']
            variation.wrist_size = sizeData['wrist_size']
            variation.full_back_length = sizeData['full_back_length']
            variation.half_back_length = sizeData['half_back_length']
            variation.full_shoulder_width = sizeData['full_shoulder_width']
            variation.stomach = sizeData['stomach']
            variation.waist_size = sizeData['waist_size']
            variation.hip_size = sizeData['hip_size']
            variation.pants_length = sizeData['pants_length']
            variation.crotch_size = sizeData['crotch_size']
            variation.fabrics = Fabric.objects.get(
                name=request.session['fabrics'])

            request.cart.add_item(variation, int(request.session['quantity']))
            recalculate_cart(request)

            return redirect("shop_cart")

    context = {"form": form}

    return render(request, template, context)
コード例 #27
0
def update_cart(request, template="shop/includes/offcanvas_cart.html", cart_formset_class=OffCartItemFormSet):
    """
    Display cart and handle removing items from the cart.
    """
    cart_formset = cart_formset_class(instance=request.cart)

    if request.is_ajax():
        if request.POST and request.POST.get("update_cart"):
            valid = request.cart.has_items()
            if not valid:
                # Session timed out.
                info(request, _("Your cart has expired"))
            else:
                cart_formset = cart_formset_class(request.POST, instance=request.cart)
                valid = cart_formset.is_valid()
                if valid:
                    cart_formset.save()
                    info(request, _("Cart updated"))
                    recalculate_cart(request)
                    cart_formset = cart_formset_class(instance=request.cart)
                else:
                    # Reset the cart formset so that the cart
                    # always indicates the correct quantities.
                    # The user is shown their invalid quantity
                    # via the error message, which we need to
                    # copy over to the new formset here.
                    errors = cart_formset._errors
                    cart_formset = cart_formset_class(instance=request.cart)
                    cart_formset._errors = errors
        elif request.POST and request.POST.get("add_cart"):
            cart_formset = cart_formset_class(instance=request.cart)

        context = {"off_cart_formset": cart_formset}
        settings.clear_cache()
        return TemplateResponse(request, template, context)

    else:
        raise Http404
コード例 #28
0
ファイル: views.py プロジェクト: davit-gh/flaunt
def get_carrier(request):
	if request.is_ajax() and request.method == 'POST':
		if not request.POST.get("free_shipping"):
			carrier = request.POST['carrier']
			shipping_type = request.POST['shipping_type']
			shipping_total = float(carrier.split()[3][1:])
			settings.use_editable()
			set_shipping(request, shipping_type, shipping_total)
			recalculate_cart(request)
		else:
			shipping_type = 'Regular Shipping'
			shipping_total = 0.0
			set_shipping(request, shipping_type, shipping_total)
		
		subtotal = float(request.cart.total_price())
		discount = float(request.session.get('discount_total','0.00'))
		total = subtotal - discount + shipping_total
		total = "{0:.2f}".format(total)
		#resp = render_to_string('shop/cart.html', { 'request': request })
	return HttpResponse(json.dumps({'shipping_type' : shipping_type, 
									'shipping_total' : shipping_total, 
									'total_price' : total,
									'discount':discount,
									'subtotal':subtotal}), content_type='application/json')
コード例 #29
0
ファイル: views.py プロジェクト: davit-gh/flaunt
def get_discount(request, discount_form_class=DiscountForm):
    if request.method == 'POST' and request.is_ajax():
        discount_form = discount_form_class(request, request.POST or None)
        ship_type = request.session.get('shipping_type', 'Shipping fee:')
        ship_total = request.session.get('shipping_total', '0.00')
        valid = discount_form.is_valid()
    if valid:
        discount_form.set_discount()
        recalculate_cart(request)
        discount_total = float(request.session.get('discount_total', 0))
        return HttpResponse(json.dumps({
            'discount_total':
            "{0:.2f}".format(discount_total),
            'cart_total':
            float(request.cart.total_price()),
            'shipping_total':
            ship_total,
            'shipping_type':
            ship_type
        }),
                            mimetype="application/json")
    else:
        return HttpResponse(json.dumps(discount_form.errors),
                            content_type="application/json")
コード例 #30
0
ファイル: shit_views.py プロジェクト: BigAN/OztrendDelpoy
def wishlist(request, template="shop/wishlist1.html"):
    """
    Display the wishlist and handle removing items from the wishlist and
    adding them to the cart.
    """
    if not settings.SHOP_USE_WISHLIST:
        raise Http404

    skus = request.wishlist
    error = None
	
    if request.method == "POST":
        print request.POST
        print "nihao"
        to_cart = request.POST.get("add_cart")
        print len(to_cart)
        print "to_cart:"+to_cart
        #{u'sku': [u'28'], u'csrfmiddlewaretoken': [u'P5IBTacZNNoP6QzaVPMScIdje3cGBEbv'], u'add_cart': [u'Buy'], u'quantity': [u'1']}>
        # test={u'sku': [u'28'], u'csrfmiddlewaretoken': [u'P5IBTacZNNoP6QzaVPMScIdje3cGBEbv'], u'add_cart': [u'Buy'], u'quantity': [u'1']}
        
        # add_product_form = AddProductForm(test or None,
        #                                   to_cart=to_cart)
        # # print request.POST
        # print add_product_form
        if len(to_cart)>10:
            pass
            tmp_post=request.POST.copy()
            wish_skus=tmp_post.getlist("sku")
            if wish_skus=="none":
                message = _("error in wishlist")
            # print "wish_skus:" + wish_skus
            for i in wish_skus:
                tmp_post.__setitem__("sku",i)
                add_product_form = AddProductForm(tmp_post or None,
                                         to_cart=to_cart)
                if add_product_form.is_valid():
                    request.cart.add_item(add_product_form.variation, 1)
                    recalculate_cart(request)
                else:
                    error = list(add_product_form.errors.values())[0]   
                # print "error:"+str(skus)
                
                skus.remove(i) 
            message = _("Items added to cart")
            url = "shop_cart"        
        elif to_cart:
            add_product_form = AddProductForm(request.POST or None,
                                         to_cart=to_cart)
        
            if add_product_form.is_valid():
                request.cart.add_item(add_product_form.variation, 1)
                print add_product_form.variation
                recalculate_cart(request)
                message = _("Item added to cart")
                url = "shop_cart"
            else:
                error = list(add_product_form.errors.values())[0]
        else:
            add_product_form = AddProductForm(request.POST or None,
                                         to_cart=to_cart)
            message = _("Item removed from wishlist")
            url = "shop_wishlist"
        sku = request.POST.get("sku")
        print request.POST.get("sku")
        print skus
        if sku in skus:
            skus.remove(sku)
        if not error:
            info(request, message)
            response = redirect(url)
            set_cookie(response, "wishlist", ",".join(skus))
            return response

    # Remove skus from the cookie that no longer exist.
    published_products = Product.objects.published(for_user=request.user)
    f = {"product__in": published_products, "sku__in": skus}
    wishlist = ProductVariation.objects.filter(**f).select_related(depth=1)
    wishlist = sorted(wishlist, key=lambda v: skus.index(v.sku))
    context = {"wishlist_items": wishlist, "error": error}
    response = render(request, template, context)
    if len(wishlist) < len(skus):
        skus = [variation.sku for variation in wishlist]
        set_cookie(response, "wishlist", ",".join(skus))
    return response
コード例 #31
0
def product(request, slug, template="shop/product.html",
            form_class=AddProductForm):
    """
    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 = 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_wishlist") is None)
    initial_data = {}
    if variations:
        initial_data = dict([(f, getattr(variations[0], f)) for f in fields])
    initial_data["quantity"] = 1
    add_product_form = form_class(request.POST or None, product=product,
                                  initial=initial_data, to_cart=to_cart)
    if request.method == "POST":
        if add_product_form.is_valid():
            if 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(request.path)
            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
    related = []
    if settings.SHOP_USE_RELATED_PRODUCTS:
        related = product.related_products.published(for_user=request.user)
    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": related,
        "add_product_form": add_product_form,
        "categories": product.categories.all()[0].get_ascendants()[::-1] + [product.categories.all()[0]]
    }
    # templates = [u"shop/%s.html" % str(product.slug), template]
    templates = []
    # Check for a template matching the page's content model.
    if product.content_model is not None and product.content_model != 'product':
        templates.append(u"shop/products/%s.html" % product.content_model)
        context["characteristics"] = product.get_content_model().get_characteristics()
        if product.content_model in ('productportal', 'productfacing'):
            context["suitable_hearth"] = product.get_content_model().suitable_hearth.published(for_user=request.user)
            context["suitable_topka"] = product.get_content_model().suitable_topka.published(for_user=request.user)
        if product.content_model in ('producthearth', 'producttopka'):
            context["suitable_faces"] = product.get_content_model().suitable_faces.published(for_user=request.user)
            context["suitable_portals"] = product.get_content_model().suitable_portals.published(for_user=request.user)
    templates.append(template)

    return render(request, templates, context)
コード例 #32
0
def membership_confirm(request,
                       level,
                       template="profiles/membership_confirm.html"):
    """
    http://stackoverflow.com/questions/38566456/how-to-run-a-celery-worker-on-aws-elastic-beanstalk
    http://stackoverflow.com/questions/12813586/running-pythons-celery-on-elastic-beanstalk-with-django
    http://stackoverflow.com/questions/14761468/how-do-you-run-a-worker-with-aws-elastic-beanstalk
    http://stackoverflow.com/questions/26851257/can-celery-run-on-elastic-beanstalk
    http://stackoverflow.com/questions/41231489/run-celery-with-django-on-aws-elastic-beanstalk-using-environment-variables
    https://www.caktusgroup.com/blog/2011/12/19/using-django-and-celery-amazon-sqs/
    http://kronosapiens.github.io/blog/2015/04/28/rabbitmq-aws.html
    http://stackoverflow.com/questions/8048556/celery-with-amazon-sqs
    http://pkj.no/2015/12/deploying-modern-django-apps-to-aws-beanstalk/
    https://www.reddit.com/r/django/comments/3eei3s/celery_and_aws/
    http://stackoverflow.com/questions/15079176/should-django-model-object-instances-be-passed-to-celery

    vvvvvvvvvvvvvvvv
    http://docs.celeryproject.org/en/latest/getting-started/brokers/sqs.html
    ^^^^^^^^^^^^^^^^^
    :param request:
    :param level:
    :param template:
    :return:
    """
    if level not in ["regular", "gold", "diamond"]:
        return redirect("change_membership_view")
    confirm_level = settings.MEMBERSHIPS[level]
    lookup = {"user": request.user}
    membership = get_object_or_404(Membership,
                                   **lookup)  # get user's membership object
    form = ConfirmationForm(request.POST or None, initial={'level': level})
    if request.method == "POST" and form.is_valid():
        # published_products = Product.objects.published(for_user=request.user)
        # if chosen membership product doesn't exist, create it, and its default variation
        member_product, created = Product.objects.get_or_create(
            slug=level,
            unit_price=settings.MEMBERSHIPS[level]["price"][0],
            # price_hkd=settings.MEMBERSHIPS[level]["price"][1],
            title="{} Membership".format(level.upper()),
            description="{} membership".format(
                level.upper()))  # slug for each membership would be EN
        if created:
            variation, created_var = ProductVariation.objects.get_or_create(
                product=member_product,
                unit_price=settings.MEMBERSHIPS[level]["price"][0],
                price_hkd=settings.MEMBERSHIPS[level]["price"][1],
                default=True)
        member_product = member_product.variations.first(
        )  # this gets first variation, which has a sku, or just made
        quantity = 1
        request.cart.add_item(member_product, quantity)
        recalculate_cart(request)
        info(request, _("Your membership will activate after purchase"))
        # check purchase 15 minutes
        # check_membership_purchase_task.apply_async((request.user.id,level),countdown=15)
        return redirect("shop_cart")
    context = {
        "membership": membership,
        "confirm_level": confirm_level,
        "form": form,
        "submit_btn": _("Confirm membership"),
        "title": level.capitalize()
    }
    return TemplateResponse(request, template, context)


#
# def test_aws_revoke(request):
#     from celery.result import AsyncResult
#     from celery.task.control import revoke
#     print("testing revoke")
#     test_task = test_aws_revoke_task.apply_async(countdown=15)
#     test_task.revoke()
#     return TemplateResponse(request, template="test/test-revoke.html",context=None)
コード例 #33
0
ファイル: views.py プロジェクト: seethersan/gandi-client
def buscarDominio(request):
    resultado = ''
    domain = ''
    dominio = ''
    extension = ''
    precio = ''
    duracion = 1
    descripcion = ''
    precio_total = ''
    price_unit = ''
    if request.method == 'POST' and 'buscar' in request.POST:
        consulta = BuscarDominioForm(request.POST)
        if consulta.is_valid():
            dominio = consulta.cleaned_data['dominio']
            extension = consulta.cleaned_data['extension']
            duracion = consulta.cleaned_data['duracion']
            duracion = int(duracion)
            request.session['dur'] = duracion
            dominio = str(dominio)
            sufijo = str(extension)
            domain = dominio + '.' + sufijo
            request.session['dom'] = domain
            result = api.domain.available(apikey, [domain])
            while result[domain] == 'pending':
                time.sleep(0.7)
                result = api.domain.available(apikey, [domain])
                if result[domain] == 'available':
                    resultado = domain + ' se encuentra disponible'
                    product_spec = {
                        'product': {
                            'description': domain,
                            'type': 'domain'
                        },
                        'action': {
                            'name': 'create',
                            'duration': duracion
                        }
                    }
                    result = api.catalog.list(apikey, product_spec)
                    result2 = result[0]
                    price = result2['unit_price']
                    price2 = price[0]
                    price_unit = price2['price']
                    precio = (price_unit + 4) * 4
                    request.session['pr_un'] = price_unit
                    request.session['pre'] = precio
                    precio_total = precio * duracion
                    break
                elif result[domain] == 'unavailable':
                    resultado = domain + ' no se encuentra disponible'
                    break
                request.session['res'] = resultado
    elif request.method == 'POST' and 'registro' in request.POST:
        producto = Product()
        dominio = request.session.get('dom')
        dominio = str(dominio)
        unit_price = request.session.get('pr_un')
        sale_price = request.session.get('pre')
        producto.unit_price = unit_price
        producto.sale_price = sale_price
        producto.num_in_stock = 30
        producto.sku = Product.objects.all().count() + 1
        duracion = request.session.get('dur')
        producto.available = True
        producto.title = dominio
        producto.save()
        product = ProductVariation()
        product.product = producto
        product.unit_price = unit_price
        product.sale_price = sale_price
        product.num_in_stock = 30
        product.sku = ProductVariation.objects.all().count() + 1
        product.save()
        request.cart.add_item(product, duracion)
        recalculate_cart(request)
        return HttpResponseRedirect('/shop/cart/')
    else:
        consulta = BuscarDominioForm()
    return render_to_response('buscadominioform.html', {
        'consulta': consulta,
        'resultado': resultado,
        'precio': precio_total
    },
                              context_instance=RequestContext(request))
コード例 #34
0
def product(request,
            slug,
            template="shop/product.html",
            form_class=AddProductForm,
            extra_context=None):
    """
    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 = 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_wishlist") is None)
    initial_data = {}
    if variations:
        initial_data = dict([(f, getattr(variations[0], f)) for f in fields])
    initial_data["quantity"] = 1
    add_product_form = form_class(request.POST or None,
                                  product=product,
                                  initial=initial_data,
                                  to_cart=to_cart)
    if request.method == "POST":
        if add_product_form.is_valid():
            if 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
    related = []
    if settings.SHOP_USE_RELATED_PRODUCTS:
        related = product.related_products.published(for_user=request.user)
    try:
        # set title = membership level + product slug ("statue+gold")
        # discount = DiscountCode.objects.filter(title="{}+{}".format(product.sku, request.user.membership.level))[0]
        discount = get_or_update_discount(request, sku=product.sku)
        # discount_percent = (100 - discount.discount_percent)/100
        discount_deduction = discount.discount_deduct
    except:
        discount_deduction = 0
    try:
        c = CurrencyRates()
        hkd_rate = c.get_rate('CNY', 'HKD')
    except:
        hkd_rate = 1.1584

    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": related,
        "add_product_form": add_product_form,
        "discount": discount_deduction,
        "hkd_rate": hkd_rate
    }
    context.update(extra_context or {})
    templates = [u"shop/%s.html" % str(product.slug), template]
    return TemplateResponse(request, templates, context)
コード例 #35
0
ファイル: views.py プロジェクト: jbmckeon/cartridge
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)
コード例 #36
0
ファイル: views.py プロジェクト: obsjames/cartridge
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.
    """

    address = request.session['address']
    if 'cart loaded' in request.session:
        current_store = request.session['stores'][0]
    else:
	current_store = []

    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_wishlist") is None)
    initial_data = {}
    if variations:
        initial_data = dict([(f, getattr(variations[0], f)) for f in fields])
    initial_data["quantity"] = 1
    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 to_cart:

                if 'cart loaded' in request.session:
                    current_store = Store.objects.filter(name__exact=product.store)[0]
                    if current_store != request.session['stores'][0]:
			info(request, _("Sorry, the item cannot be added to your cart. "
					"By NY law you cannot shop from two different liquor stores simultaneously."))
                        return HttpResponseRedirect('/shop/')
                else:
                    request.session['cart loaded'] = 'cart loaded'
                    store = Store.objects.filter(name__exact=product.store)
                    request.session['stores'] = store
                    request.session['delivery min'] = store[0].delivery_min

		    current_store = store[0]

    		name = unicodedata.normalize('NFKD', current_store.name).encode('ascii','ignore')
    		store_slug = '/shop/'+slugify(name)+'/'
    		request.session['store slug'] = store_slug

                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. Anything else from %s?" % name ))
#                return redirect("shop_cart")
		return redirect(store_slug)

            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,
	"address": address,
	"stores": current_store,
    }
    templates = [u"shop/%s.html" % unicode(product.slug), template]  # new
    return render(request, templates, context)
コード例 #37
0
ファイル: views.py プロジェクト: obsjames/cartridge
def cart(request, template="shop/cart.html"):
    """
    Display cart and handle removing items from the cart.
    """
    if 'delivery min' in request.session:
        delivery_min = request.session['delivery min']
    else:
        delivery_min = []

    if 'store slug' in request.session:
	store_slug = request.session['store slug']
    else:
	store_slug = '/shop/'

    address = request.session['address']
    current_store = []
    if 'cart loaded' in request.session:
        current_store = request.session['stores'][0]

    cart_formset = CartItemFormSet(instance=request.cart)
    discount_form = DiscountForm(request, request.POST or None)

    tax_handler(request, None)

    if request.method == 'POST':
        tipform = TipForm(request.POST)
        if tipform.is_valid():
            tip_percent = tipform.cleaned_data['tip']
	    tip = 0.01*float(tip_percent)*float(request.cart.total_price())

            billship_handler(request, tip)
#    	    tax_handler(request, None)
            request.session['tip fixed'] = True
    else:
        tipform = TipForm()

    if 'shop_checkout' in request.POST:
                return redirect('/shop/checkout')
    elif request.method == "POST":
        valid = True
        if request.POST.get("update_cart"):
            valid = request.cart.has_items()
            if not valid:
                # Session timed out.
                if 'stores' in request.session:
                    del request.session['stores']
                if 'cart loaded' in request.session:
                    del request.session['cart loaded']
                info(request, _("Your cart has expired"))
		return redirect('/shop/')
            else:
                cart_formset = CartItemFormSet(request.POST,
                                               instance=request.cart)
                valid = cart_formset.is_valid()
                if valid:
                    cart_formset.save()
                    recalculate_cart(request)
                    info(request, _("Cart updated"))
                else:
                    # Reset the cart formset so that the cart
                    # always indicates the correct quantities.
                    # The user is shown their invalid quantity
                    # via the error message, which we need to
                    # copy over to the new formset here.
                    errors = cart_formset._errors
                    cart_formset = CartItemFormSet(instance=request.cart)
                    cart_formset._errors = errors
        else:
            valid = discount_form.is_valid()
            if valid:
                discount_form.set_discount()

        if valid:
            total_quantity, number_forms, number_items_removed = 0, 0, 0
            for form in cart_formset:
                number_forms += 1
                if form.is_valid():
                    was_item_removed = form.cleaned_data["DELETE"]
                    if was_item_removed:
                        number_items_removed += 1
                    total_quantity += form.cleaned_data["quantity"]
            if number_forms==number_items_removed:
                if 'stores' in request.session:
                    del request.session['stores']
                if 'cart loaded' in request.session:
                    del request.session['cart loaded']
		return redirect('/shop/')
            elif total_quantity==0:
                if 'stores' in request.session:
                    del request.session['stores']
                if 'cart loaded' in request.session:
                    del request.session['cart loaded']
#            return redirect("shop_cart")
	    	return redirect('/shop/')

    ten_percent = 0.1*float(request.cart.total_price())
    suggested_tip = '%.2f' % float((ten_percent>2.0)*ten_percent+(ten_percent <=2.0)*2.0)
    if 'tip fixed' in request.session:
        tip_fixed = True
    else:
        tip_fixed = False
    context = {"cart_formset": cart_formset, "delivery_min": delivery_min, "tipform": tipform,
               "suggested_tip": suggested_tip, "tip_fixed": tip_fixed, "store_slug": store_slug,
	       "address": address, "stores": current_store}
    settings.use_editable()
    if (settings.SHOP_DISCOUNT_FIELD_IN_CART and
        DiscountCode.objects.active().count() > 0):
        context["discount_form"] = discount_form
    return render(request, template, context)
コード例 #38
0
ファイル: views.py プロジェクト: hderaps/bccf
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)
    if not request.is_ajax():
        page = Category.objects.get(slug__exact='shop')
        products = Product.objects.published(for_user=request.user
                                    ).filter(page.category.filters()).distinct()
        sort_options = [(slugify(option[0]), option[1])
                        for option in settings.SHOP_PRODUCT_SORT_OPTIONS]
        sort_by = request.GET.get("sort", sort_options[0][1])
        products = paginate(products.order_by(sort_by),
                            request.GET.get("page", 1),
                            settings.SHOP_PER_PAGE_CATEGORY,
                            settings.MAX_PAGING_LINKS)
        products.sort_by = sort_by
        sub_categories = page.category.children.published()
        child_categories = Category.objects.filter(id__in=sub_categories)
        context = RequestContext(request, locals())
        return render_to_response('pages/category.html', {}, context_instance=context)
    else: 
        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_wishlist") is None)
        initial_data = {}
        if variations:
            initial_data = dict([(f, getattr(variations[0], f)) for f in fields])
        initial_data["quantity"] = 1
        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 to_cart:
                    quantity = add_product_form.cleaned_data["quantity"]
                    request.cart.add_item(add_product_form.variation, quantity)
                    recalculate_cart(request)
                    return HttpResponse(request.cart.total_quantity())
                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)
コード例 #39
0
ファイル: accounts.py プロジェクト: hderaps/bccf
def membership_voting(request, type):
    variation = ProductVariation.objects.get(sku=type)
    request.cart.add_item(variation, 1)
    recalculate_cart(request)
    response = redirect('shop_checkout')
    return response
コード例 #40
0
ファイル: views.py プロジェクト: jaywink/cartridge-reservable
def product(request, slug, template="shop/product.html",
            form_class=AddProductForm):
    """
    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 = 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_wishlist") is None)
    initial_data = {}
    if variations:
        initial_data = dict([(f, getattr(variations[0], f)) for f in fields])
    initial_data["quantity"] = 1
    add_product_form = form_class(request.POST or None, product=product,
                                  initial=initial_data, to_cart=to_cart)
    if request.method == "POST":
        if add_product_form.is_valid():
            if to_cart:
                quantity = add_product_form.cleaned_data["quantity"]
                if product.content_model == 'reservableproduct':
                    from_date = add_product_form.cleaned_data["from_date"]
                    to_date = add_product_form.cleaned_data["to_date"]
                else:
                    from_date = None
                    to_date = None
                request.cart.add_item(add_product_form.variation, quantity, from_date, to_date)
                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
    related = []
    if settings.SHOP_USE_RELATED_PRODUCTS:
        related = product.related_products.published(for_user=request.user)
    if product.content_model == 'reservableproduct':
        reservable = ReservableProduct.objects.get(id=product.id)
        reservations = reservable.reservations.all()
    else:
        reservations = None
        reservable = None
    timespecials = product.specialprices.filter(special_type='PER', to_date__gte=date.today())
    try:
        weekendspecial = product.specialprices.get(special_type='WKD')
    except SpecialPrice.DoesNotExist:
        weekendspecial = False
    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": related,
        "add_product_form": add_product_form,
        "reservations": reservations,
        "reservable": reservable,
        "timespecials": timespecials,
        "weekendspecial": weekendspecial,
    }
    templates = [u"shop/%s.html" % str(product.slug), template]
	# Check for a template matching the page's content model.
    if product.content_model is not None:
        templates.insert(0, u"shop/products/%s.html" % product.content_model)
    templates.append(template)
    return render(request, templates, context)
コード例 #41
0
def design(request, product_slug, shop_slug,
                     template="mukluk/designed_product.html",
                     form_class=AddProductForm, extra_context=None):
    published_dps = DesignedProduct.objects.published(for_user=request.user)
    designed_product = get_object_or_404(published_dps, slug=product_slug)
    base = get_object_or_404(Product, slug=designed_product.base.slug)

    fields = [f.name for f in ProductVariation.option_fields()]
    variations = base.variations.all()
    variations_json = 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_wishlist") is None)

    initial_data = {}
    if variations:
        initial_data = dict([(f, getattr(variations[0], f)) for f in fields])
    initial_data["quantity"] = 1
    add_product_form = form_class(request.POST or None, product=base,
                                  initial=initial_data, to_cart=to_cart)
    if request.method == "POST":
        if add_product_form.is_valid():
            if to_cart:
                quantity = add_product_form.cleaned_data["quantity"]
                request.cart.add_item(
                    add_product_form.variation, designed_product, 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

    # related = []
    # if settings.SHOP_USE_RELATED_PRODUCTS:
    #     related = product.related_products.published(for_user=request.user)

    context = {
        "designed_product": designed_product,
        "product": base,
        "editable_obj": designed_product,
        "images": designed_product.images.all(),
        "variations": variations,
        "variations_json": variations_json,
        "has_available_variations": any([v.has_price() for v in variations]),
        # "related_products": related,
        "add_product_form": add_product_form
    }
    context.update(extra_context or {})

    templates = [u"mukluk/%s.html" % str(designed_product.slug), template]
    # Check for a template matching the page's content model.
    if getattr(designed_product, 'content_model', None) is not None:
        templates.insert(0, u"shop/products/%s.html" % designed_product.content_model)

    return TemplateResponse(request, templates, context)
コード例 #42
0
def product(request,
            slug,
            template="shop/product.html",
            form_class=AddProductForm):
    """
    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 = 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_wishlist") is None)
    initial_data = {}
    if variations:
        initial_data = dict([(f, getattr(variations[0], f)) for f in fields])
    initial_data["quantity"] = 1
    add_product_form = form_class(request.POST or None,
                                  product=product,
                                  initial=initial_data,
                                  to_cart=to_cart)
    if request.method == "POST":
        if add_product_form.is_valid():
            if 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(request.path)
            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
    related = []
    if settings.SHOP_USE_RELATED_PRODUCTS:
        related = product.related_products.published(for_user=request.user)
    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":
        related,
        "add_product_form":
        add_product_form,
        "categories":
        product.categories.all()[0].get_ascendants()[::-1] +
        [product.categories.all()[0]]
    }
    # templates = [u"shop/%s.html" % str(product.slug), template]
    templates = []
    # Check for a template matching the page's content model.
    if product.content_model is not None and product.content_model != 'product':
        templates.append(u"shop/products/%s.html" % product.content_model)
        context["characteristics"] = product.get_content_model(
        ).get_characteristics()
        if product.content_model in ('productportal', 'productfacing'):
            context["suitable_hearth"] = product.get_content_model(
            ).suitable_hearth.published(for_user=request.user)
            context["suitable_topka"] = product.get_content_model(
            ).suitable_topka.published(for_user=request.user)
        if product.content_model in ('producthearth', 'producttopka'):
            context["suitable_faces"] = product.get_content_model(
            ).suitable_faces.published(for_user=request.user)
            context["suitable_portals"] = product.get_content_model(
            ).suitable_portals.published(for_user=request.user)
    templates.append(template)

    return render(request, templates, context)
コード例 #43
0
ファイル: views.py プロジェクト: seethersan/gandi-client
def buscarDominio(request):
	resultado = ''
	domain = ''
	dominio = ''
	extension = ''
	precio = ''
	duracion = 1
	descripcion = ''
	precio_total = ''
	price_unit = ''
        if request.method=='POST' and 'buscar' in request.POST:
                consulta = BuscarDominioForm(request.POST)
                if consulta.is_valid():
                        dominio = consulta.cleaned_data['dominio']
			extension = consulta.cleaned_data['extension']
			duracion = consulta.cleaned_data['duracion']
			duracion = int(duracion)
			request.session['dur'] = duracion
			dominio = str(dominio)
			sufijo = str(extension)
			domain = dominio + '.' + sufijo
			request.session['dom'] = domain
			result = api.domain.available(apikey, [domain])
	                while result[domain]  == 'pending':
        	        	time.sleep(0.7)
                		result = api.domain.available(apikey, [domain])
				if result[domain] == 'available':
					resultado = domain + ' se encuentra disponible'
					product_spec = {
						'product' : {
							'description': domain,
							'type': 'domain'
						},
						'action' : {
							'name': 'create',
							'duration': duracion
						}
					}
					result = api.catalog.list(apikey, product_spec)
					result2 = result[0]
					price = result2['unit_price']
					price2 = price[0]
					price_unit = price2['price']
					precio = (price_unit + 4)*4
					request.session['pr_un'] = price_unit
					request.session['pre'] = precio
					precio_total = precio*duracion
					break
				elif result[domain] == 'unavailable':
					resultado = domain + ' no se encuentra disponible'
					break
				request.session['res'] = resultado
        elif request.method == 'POST' and 'registro' in request.POST:
		producto = Product()
                dominio = request.session.get('dom')
		dominio = str(dominio)
                unit_price = request.session.get('pr_un')
               	sale_price = request.session.get('pre')
		producto.unit_price = unit_price
		producto.sale_price = sale_price
		producto.num_in_stock = 30
		producto.sku = Product.objects.all().count() + 1
                duracion = request.session.get('dur')
		producto.available = True
		producto.title = dominio
		producto.save()
                product = ProductVariation()
                product.product = producto
		product.unit_price = unit_price
		product.sale_price = sale_price
		product.num_in_stock = 30
		product.sku = ProductVariation.objects.all().count() + 1
		product.save()
                request.cart.add_item(product, duracion)
		recalculate_cart(request)
		return HttpResponseRedirect('/shop/cart/')
        else:
                consulta = BuscarDominioForm()
        return render_to_response('buscadominioform.html',{'consulta':consulta, 'resultado':resultado, 'precio':precio_total}, context_instance=RequestContext(request))
コード例 #44
0
ファイル: views.py プロジェクト: LANtasy/website
 def form_valid(self, form):
     quantity = form.cleaned_data["quantity"]
     self.request.cart.add_item(form.ticket_option, quantity)
     recalculate_cart(self.request)
     info(self.request, 'Item added to cart')
     return redirect("shop_cart")
コード例 #45
0
ファイル: views.py プロジェクト: BigAN/OztrendDelpoy
def wishlist(request, template="shop/wishlist1.html"):
    """
    Display the wishlist and handle removing items from the wishlist and
    adding them to the cart.
    """
    if not settings.SHOP_USE_WISHLIST:
        raise Http404

    skus = request.wishlist
    error = None
    # print "hehe"
    if request.method == "POST":
        # print request.POST
        print "nihao"
        # to_cart = request.POST.get("add_cart").decode('utf-8').encode('GBK')
        to_cart = request.POST.get("add_cart")
        if to_cart:
            tmp_post=request.POST.copy()
            wish_skus=tmp_post.getlist("sku")
            if wish_skus=="none":
                message = _("error in wishlist")
            # print "wish_skus:" + wish_skus
            for i in wish_skus:
                tmp_post.__setitem__("sku",i)
                add_product_form = AddProductForm(tmp_post or None,
                                         to_cart=to_cart)
                if add_product_form.is_valid():
                    request.cart.add_item(add_product_form.variation, 1)
                    recalculate_cart(request)
                else:
                    error = list(add_product_form.errors.values())[0]   
                # print "error:"+str(skus)
                
                skus.remove(i) 
            message = _("Items added to cart")
            url = "shop_cart"        
        else:
            add_product_form = AddProductForm(request.POST or None,
                                         to_cart=to_cart)
            message = _("Item removed from wishlist")
            url = "shop_wishlist"
        sku = request.POST.get("sku")
        print request.POST.get("sku")
        print skus
        if sku in skus:
            skus.remove(sku)
        if not error:
            info(request, message)
            response = redirect(url)
            set_cookie(response, "wishlist", ",".join(skus))
            return response

    # Remove skus from the cookie that no longer exist.
    published_products = Product.objects.published(for_user=request.user)
    f = {"product__in": published_products, "sku__in": skus}
    wishlist = ProductVariation.objects.filter(**f).select_related(depth=1)
    wishlist = sorted(wishlist, key=lambda v: skus.index(v.sku))
    context = {"wishlist_items": wishlist, "error": error}
    response = render(request, template, context)
    if len(wishlist) < len(skus):
        skus = [variation.sku for variation in wishlist]
        set_cookie(response, "wishlist", ",".join(skus))
    return response