Exemple #1
0
def update_cart(request, product_id):
    request.session.set_expiry(120000)
    print(request.session.__dict__)
    try:
        the_id = request.session['cart_id']
    except:
        new_cart = Cart()
        new_cart.save()
        request.session['cart_id'] = new_cart.id
        the_id = new_cart.id
    cart = get_object_or_404(Cart, id=the_id)
    product = get_object_or_404(Product, id=product_id)
    product.amount = 1
    product.save()
    cart_item, created = CartItem.objects.get_or_create(product=product)

    if not cart_item in cart.items.all():
        cart_item.amount = 1
        cart_item.save()
        cart.items.add(cart_item)
    else:
        cart.items.remove(cart_item)

    new_total = 0.00
    for item in cart.items.all():
        new_total += float(item.get_full_price())
    request.session['items_total'] = cart.items.count()
    if not request.session['items_total']:
        return redirect('to_home_url')
    cart.total = new_total
    cart.save()
    return redirect('view_cart_url')
Exemple #2
0
def add_ajax(request):
    if request.is_ajax() and request.POST:
        try:
            id = request.session['cart_id']
        except:
            new_cart = Cart()
            new_cart.save()
            request.session['cart_id'] = new_cart.id
            id = new_cart.id

        slug = request.POST['slug']
        qty = request.POST['qty']
        
        cart = get_object_or_404(Cart, id=id)
        product = get_object_or_404(Products, slug=slug)

        cart_item = CartItem.objects.create(cart=cart, product=product)
        cart_item.save()
        cart_item.quantity = qty
        cart_item.line_total = int(cart_item.quantity) * int(cart_item.product.price)
        cart_item.save()

        request.session['cart_items'] = len(cart.cartitem_set.all())
        response_data = len(cart.cartitem_set.all())
        print response_data
        return HttpResponse(json.dumps(response_data), content_type='application/json')
Exemple #3
0
 def post(self, req):
     d = req.data
     username = d.get('username')
     email = d.get('email')
     pwd = d.get('password')
     user = User.objects.filter(email=email)
     if user:
         return Response({'error':
                          'An account with that email already exists.'},
                         status=409)
     user = User.objects.filter(username=username)
     if user:
         return Response({'error':
                          'An account with that username already exists.'},
                         status=409)
     if len(pwd) < settings.MIN_PASSWORD_LENGTH:
         return Response({'error':
                          'Password must be at least {} characters long'
                          .format(settings.MIN_PASSWORD_LENGTH)},
                           status=411)
     user = User.objects.create_user(username=username, email=email,
                                     password=pwd)
     if user is None:
         return Response({'error': 'There was an error creating the user.'},
                         status=500)
     cart = Cart(user=user)
     cart.save()
     url = req.build_absolute_uri('/auth/confirm-email')
     uid = user.id * settings.EMAIL_CONFIRM_HASH_NUM
     token = account_activation_token.make_token(user)
     url += '?token={}&uid={}'.format(token, uid)
     send_acct_confirm_email.delay(user.id, url)
     return Response({'user': user.to_json()})
Exemple #4
0
    def get_form_initial(self, step):

        # steps are named 'step1', 'step2', 'step3'
        current_step = self.storage.current_step

        if step == '0':
            return self.initial_dict.get(
                step, {'temp_hash': uuid.uuid1(), 'step_description': 'Carga tus fotos y editalas'}
            )
        # get the data for step 1 on step 3
        if step == '1':
            prev_data = self.storage.get_step_data('0')
            temp_hash = prev_data.get('0-temp_hash', '')
            sorted_photo_list = self.get_images_data(temp_hash).values('id')
            return self.initial_dict.get(
                step, {'temp_hash': temp_hash, 'photo_sort_list': sorted_photo_list, }
            )

        if step == '2':

            try:
                cart_id = self.request.session['cart_id']
            except Exception as e:
                print(e)
                new_cart = Cart()
                new_cart.save()
                self.request.session['cart_id'] = new_cart.id
                cart_id = new_cart.id

            cart = Cart.objects.get(id=cart_id)
            return self.initial_dict.get(
                step, {'cart': cart, 'step_title': 'Paso 3', 'step_description': 'Revisa de tus fotos'}
            )

        return self.initial_dict.get(step, {})
Exemple #5
0
 def get_object(self, *args, **kwargs):
     self.request.session.set_expiry(0)
     cart_id = self.request.session.get("cart_id")
     if cart_id == None:
         cart = Cart()
         cart.subtotal = 0
         cart.save()
         cart_id = cart.id
         self.request.session["cart_id"] = cart_id
     cart = Cart.objects.get(id=cart_id)
     return cart
Exemple #6
0
def retrived_cart(request):
    try:
        the_id = request.session['cart_id']
    except:
        new_cart = Cart()
        new_cart.save()
        request.session['cart_id'] = new_cart.id
        the_id = new_cart.id
    cart = Cart.objects.get(id=the_id)

    return cart
Exemple #7
0
    def get_delivery(self, obj):
        request = self.context.get("request")

        cart = Cart(user=request.user)
        seller_delivery_cart_item = CartItem(
            product=obj,
            quantity=1,
            delivery_option_id=DeliveryOption.SELLER,
            cart=cart)

        options = {
            "seller": seller_delivery_cart_item.seller_delivery_fee.netto,
            "pickup": Decimal("0.0"),
        }

        region_settings = get_setting(request.region.id)
        if region_settings.central_logistics_company:
            central_logistics_cart_item = CartItem(
                product=obj,
                quantity=1,
                delivery_option_id=DeliveryOption.CENTRAL_LOGISTICS,
                cart=cart,
            )
            options[
                "logistics"] = central_logistics_cart_item.central_logistic_delivery_fee.netto

        return options
Exemple #8
0
 def update_cart_totals(cls, cart: Cart) -> Cart:
     courses = CourseSelector.get_courses_by_cart(cart=cart)
     subtotal = 0
     total = 0
     for course in courses:
         subtotal += course.price
         discount = DiscountSelector.get_discount_for_course_or_nothing(
             course=course, cart=cart)
         if discount is None:
             total += course.price
         else:
             total += discount.new_price
     cart.subtotal = subtotal
     cart.total = total
     cart.save()
     return cart
Exemple #9
0
def edit_wizard(request, cart_item_id=None):
    """

    :param request:
    :param id:
    :return: :raise HttpResponseForbidden:
    """
    cart_item = CartItem.objects.get(id=cart_item_id)
    # cart = cart_item.cart
    # order_list = cart.order_set
    # order = cart.order_set.first()
    # user = order.user
    # print(order_list)
    photo_list = cart_item.photo_set.order_by('sequence')
    sorted_photo_list = photo_list.values('id')

    # photo_list = Photo.objects.filter(temp_hash=temp_hash).order_by('sequence')
    temp_hash = photo_list.first().temp_hash
    product = cart_item.product

    try:
        cart = cart_item.cart
    except Exception as e:
        print(e)
        new_cart = Cart()
        new_cart.save()
        request.session['cart_id'] = new_cart.id
        cart_id = new_cart.id

    # cart = Cart.objects.get(id=cart_id)

    if 1 != 1:
        raise HttpResponseForbidden
    else:
        # get the initial data to include in the form
        initial = {'0': {'photo_list': photo_list, 'temp_hash': temp_hash,
                         },
                   '1': {'photo_list': photo_list, 'temp_hash': temp_hash, 'photo_sort_list': sorted_photo_list,
                         },
                   '2': {'cart': cart,
                         },
                   }
        form = UploadPhotosWizard.as_view([PhotoUploadForm, PhotoSortForm, CartItemForm], initial_dict=initial)
        return form(context=RequestContext(request), request=request, slug=product.slug, cart_item_id=cart_item_id)
Exemple #10
0
 def prepare_new_user(self, data):
     email = data.get('email', None)
     if not self.email_is_used(email):
         new_user = self.create_new_user(data)
         Cart().create_cart_to_new_user(new_user)
         user = authenticate(username=data.get('username'),
                             password=data.get('password'))
         self.get_token(user)
         return new_user
     raise serializers.ValidationError(
         {'email_used': _('This email is already used.')})
Exemple #11
0
    def get_object(self, *args, **kwargs):
        self.request.session.set_expiry(0)  # 1800 seconds = 1800.
        cart_id = self.request.session.get("cart_id")

        # if session doesn't have Cart, create the Cart AND set the session [ "cart_id" ]
        if cart_id == None:
            new_cart = Cart()
            new_cart.save()
            cart_id = new_cart.id
            # = Cart.objects.create()
            self.request.session["cart_id"] = new_cart.id
        # Get the Cart. new Cart or existing Cart
        cart = Cart.objects.get(id=cart_id)

        # if user authenticated, set the user of the cart
        if self.request.user.is_authenticated():
            # cart = Cart.objects.get(id=cart_id, user=request.user)
            cart.user = self.request.user
            cart.save()

        return cart
Exemple #12
0
 def get_object(self, *args, **kwargs):
     self.request.session.set_expiry(0)  #5 minutes
     cart_id = self.request.session.get("cart_id")
     if cart_id == None:
         cart = Cart()
         cart.tax_percentage = 0.075
         cart.save()
         cart_id = cart.id
         self.request.session["cart_id"] = cart_id
     cart = Cart.objects.get(id=cart_id)
     if self.request.user.is_authenticated():
         cart.user = self.request.user
         cart.save()
     return cart
Exemple #13
0
 def register_user(self,
                   seed,
                   is_staff=False,
                   with_cart=False,
                   email_verified=False):
     """
     Helper to create a user object.
     :param seed: int
     """
     username = '******'.format(seed)
     email = '{}@example.com'.format(username)
     user = User(username=username, email=email)
     user.set_password('pass')
     if is_staff:
         user.is_staff = True
     if email_verified:
         user.email_verified = True
     user.save()
     if with_cart:
         cart = Cart(user=user)
         cart.save()
     return user
Exemple #14
0
	def get_object(self,*args, **kwargs):
		self.request.session.set_expiry(0)
		cart_id = self.request.session.get("cart_id")

		if cart_id == None:
			cart = Cart()
			cart.update_subtotal()
			cart.save()
			cart_id = cart.id
			self.request.session["cart_id"] = cart_id
		cart = Cart.objects.get(id=cart_id)
		if self.request.user.is_authenticated():
			cart.user = self.request.user
			cart.save()
		return cart
Exemple #15
0
    def post(self, *args, **kwargs):
        menu_categories, cart, cart_items = initial_data(self.request)
        if self.request.POST.get('coupon_name', None):
            code = self.request.POST.get('coupon_name', None)
            find_coupon = Coupons.objects.filter(code=code, active=True)
            if find_coupon.exists():
                coupon = find_coupon.first()
                cart.coupon.add(coupon)
                cart.save()
                messages.success(self.request,
                                 'Coupon %s added in your cart!' % code)
            else:
                messages.warning(self.request,
                                 'This code is not a valid coupon')
        if 'my_cart' in self.request.POST:
            Cart.costumer_changes(self.request, cart)
            return HttpResponseRedirect(self.request.META.get('HTTP_REFERER'))

        if 'my_cart' not in self.request.POST:
            data = self.request.POST
            for key, value in data.items():
                print(key, value)
                if value == '0':
                    continue
                else:
                    try:
                        get_item = CartItem.objects.get(id=key)
                        get_item.qty = int(value)
                        get_item.save()
                        get_item.refresh_from_db()
                    except:
                        continue
            CartGiftItem.check_cart(cart)
            messages.success(self.request, 'The cart updated!')
        cart.refresh_from_db()
        context = locals()
        return render(self.request, self.template_name, context=context)
	def get(self, request):
		self.request.session.set_expiry(0) #till browser closed

		cart_id = self.request.session.get("cartID") #you can use any name "cartID"

		#if no session exist, create new and save
		if cart_id == None:
			cart = Cart()
			cart.save()

			#save cart_id for first use.
			cart_id = cart.id # After this it will save by line 18
			self.request.session["cartID"] = cart.id #save session

		# save current cartID into cart,  for displaying cart item in template
		cart = Cart.objects.get(id=cart_id)

		#if already login, save username in Cart
		if self.request.user.is_authenticated():
			cart.user = self.request.user
			cart.save()

		#ItemID is coming from book_detail.html
		#get ItemID from url, to add the item in current session.
		item_id = request.GET.get("ItemID")

		# get the book with format from above ID
		item_instance = get_object_or_404(Format, id=item_id)

		#save the above book in cart item
		cart_item, created = CartItem.objects.get_or_create(cart=cart, item=item_instance)

		#check quantity entered by user in book_detail.html page
		qty = request.GET.get("qty")

		#get DeleteItem from url, defined in Format class
		delete_item = request.GET.get("DeleteItem")
		if int(qty) < 1:
			delete_item = True

		#both delete and qty appear on link, if DeleteItem exist then delete it,
		#otherwise set the correct quntity. 
		if delete_item:
			cart_item.delete()
		else:
			cart_item.quantity = qty
			cart_item.save()

		#update the cart variable again, before sending to view.html
		#if we remove this line, subtotal may not be updated immediately
		cart = Cart.objects.get(id=cart_id)

		context = {
			"cart": cart
		}
		template = self.template_name
		return render(request, template, context)
Exemple #17
0
 def get_object(self, *args, **kwargs):
     self.request.session.set_expiry(0)
     cart_id = self.request.session.get('cart_id')
     if cart_id is None:
         cart = Cart()
         cart.save()
         cart_id = cart.id
         self.request.session['cart_id'] = cart_id
     cart = Cart.objects.get(id=cart_id)
     if self.request.user.is_authenticated():
         cart.user = self.request.user
         cart.save()
     return cart
Exemple #18
0
def add_to_cart(request, slug):
    #Session is set to expire in 5 mins = 3000
    request.session.set_expiry(3000)
    # PRODUCT QUANTITY
    try:
        the_id = request.session['cart_id']
    except:
        new_cart = Cart()
        new_cart.save()
        request.session['cart_id'] = new_cart.id
        the_id = new_cart.id

    cart = Cart.objects.get(id=the_id)
    #ITEMS IN CART
    try:
        product = Product.objects.get(slug=slug)
    except Product.DoesNotExist:
        pass
    except:
        pass
    product_var = []  #product_var

    if request.method == "POST":
        qty = request.POST['qty']
        for item in request.POST:
            key = item
            val = request.POST[key]
        cart_item = CartItem.objects.create(cart=cart, product=product)
        print(cart_item)
        cart_item.quantity = qty
        # saving notes in a dictionary
        cart_item.save()
        # success message
        return redirect(reverse("cart"))
    #error message
    return redirect(reverse("cart"))
Exemple #19
0
 def get_object(self, *args, **kwargs):
     self.request.session.set_expiry(
         0)  #session closed when browser is closed
     cart_id = self.request.session.get("cart_id")
     if cart_id == None:
         cart = Cart()
         cart.save()
         cart_id = cart.id
         self.request.session["cart_id"] = cart_id
     cart = Cart.objects.get(id=cart_id)
     if self.request.user.is_authenticated():
         cart.user = self.request.user
         cart.save()
     return cart
    def get_cart(self, *args, **kwargs):
        cart_id = self.request.session.get('cart_id')
        if cart_id is None:
            cart = Cart()
            cart.save()
            cart_id = cart.id
            self.request.session['cart_id'] = cart_id

        cart = Cart.objects.get(id=cart_id)
        if self.request.user.is_authenticated(): # Login user
            # if the cart is not belong to the current login user,
            # start a new cart
            if cart.user is not None and cart.user != self.request.user:
                cart = Cart()
                cart.save()
                self.request.session['cart_id'] = cart.id
            cart.user = self.request.user
            cart.save()
        else: # Guest user
            if cart.user:
                pass # Required Login or remind user to start a new session
        return cart
Exemple #21
0
    def get_object(self, *args, **kwargs):
        self.request.session.set_expiry(0)  # until the browser closes
        cart_id = self.request.session.get('cart_id', None)
        if not cart_id:
            # Create cart
            cart = Cart()
            cart.save()
            cart_id = cart.id
            self.request.session['cart_id'] = cart_id

        cart = Cart.objects.get(id=cart_id)
        if self.request.user.is_authenticated():
            cart.user = self.request.user
            cart.save()
        return cart
Exemple #22
0
 def _choose_cart_by_user_or_by_id(cls, cart_by_id: Cart,
                                   cart_by_user: Cart) -> Cart:
     if cart_by_id != cart_by_user:
         if cart_by_id.user is not None and cart_by_id.user != cart_by_user.user:
             return cart_by_user
         if cart_by_user.get_courses_count != 0:
             cart_by_id.delete()
             return cart_by_user
         else:
             if cart_by_id.user is None:
                 cart_by_id.user = cart_by_user.user
                 cart_by_id.save()
             cart_by_user.delete()
             return cart_by_id
     return cart_by_id
Exemple #23
0
	def get_object(self, *args, **kwargs):
		self.request.session.set_expiry(0) #session expires on window close or 300 -> 5 min
		cart_id = self.request.session.get("cart_id")
		if cart_id == None:
			cart = Cart()
			cart.save()
			cart_id = cart.id
			self.request.session["cart_id"] = cart_id
		cart = Cart.objects.get(id=cart_id)
		if self.request.user.is_authenticated():
			cart.user = self.request.user
			cart.save()

		citems = CartItem.objects.filter(cart=cart)
		for citem in citems:
			if citem.item.available_quantity <= 0:
				citem.out_of_stock = True
				citem.line_item_total = 0.0
			else:
				citem.out_of_stock = False
			citem.save()
		cart.update_subtotal()
		return cart
Exemple #24
0
    def get_object(self, *args, **kwargs):
        # Expire the session after 5 mins - put 300
        # To expire once the browser is closed use 0
        self.request.session.set_expiry(0)
        cart_id = self.request.session.get("cart_id")
        if cart_id is None:
            cart = Cart()
            cart.save()
            cart_id = cart.id
            self.request.session["cart_id"] = cart_id

        cart = Cart.objects.get(id=cart_id)
        if self.request.user.is_authenticated():
            cart.user = self.request.user
            cart.save()
        return cart
Exemple #25
0
    def get_cart(self):
        data, cart_obj, response_status = self.get_cart_from_token()
        if cart_obj == None or not cart_obj.active:
            cart = Cart()
            cart.tax_percentage = 0.075
            if self.request.user.is_authenticated():
                cart.user = self.request.user
            cart.save()
            data = {"cart_id": str(cart.id)}
            self.create_token(data)
            cart_obj = cart

        return cart_obj
Exemple #26
0
 def get_object(self, *args, **kwargs):
     self.request.session.set_expiry(0)
     cart_id = self.request.session.get('cart_id')
     if cart_id is None:
         cart = Cart()
         cart.save()
         cart_id = cart.id
         self.request.session['cart_id'] = cart_id
     cart = Cart.objects.get(id=cart_id)
     if self.request.user.is_authenticated():
         cart.user = self.request.user
         cart.save()
     return cart
Exemple #27
0
 def get_object(self, *args, **kwargs):
     # 5 min
     self.request.session.set_expiry(300)
     cart_id = self.request.session.get("cart_id")
     if None == cart_id:
         cart = Cart()
         cart.save()
         cart_id = cart.id
         self.request.session["cart_id"] = cart_id
     cart = Cart.objects.get(id=cart_id)
     if self.request.user.is_authenticated():
         cart.user = self.request.user
         cart.save()
     return cart
Exemple #28
0
    def get_object(self, *args, **kwargs):
        #*************************single object mixin ......copying the get data stuff from the get function
        # replace request to self.request
        # session expiry
        self.request.session.set_expiry(0)# when web browser is closed
        #create session
        cart_id = self.request.session.get("cart_id")

        if cart_id == None:
            cart = Cart() # create new cart
            cart.save()
            cart_id = cart.id
            self.request.session['cart_id'] = cart_id

        cart = Cart.objects.get(id=cart_id)

        if self.request.user.is_authenticated():
            cart.user = self.request.user
            cart.save()
        return cart
Exemple #29
0
def m2m_changed_cart_receiver(sender, instance: Cart, action, *args, **kwargs):
    if "post_" in action:
        instance.update_totals()
Exemple #30
0
    def get_cart(self, *args, **kwargs):
        cart_id = self.request.session.get('cart_id')
        if cart_id is None:
            cart = Cart()
            cart.save()
            cart_id = cart.id
            self.request.session['cart_id'] = cart_id

        cart = Cart.objects.get(id=cart_id)
        if self.request.user.is_authenticated():  # Login user
            # if the cart is not belong to the current login user,
            # start a new cart
            if cart.user is not None and cart.user != self.request.user:
                cart = Cart()
                cart.save()
                self.request.session['cart_id'] = cart.id
            cart.user = self.request.user
            cart.save()
        else:  # Guest user
            if cart.user:
                pass  # Required Login or remind user to start a new session
        return cart
Exemple #31
0
def course_post_save_receiver(sender, instance, **kwargs):
    from carts.models import Cart
    carts = Cart.objects.all()  # TODO: Change this so that it exclude those irrelevant carts
    for cart in carts:
        cart.total = Cart.calculate_new_total(cart)
        cart.save()
Exemple #32
0
def edit(request, pizza_id):
    if request.method == "POST":
        try:
            the_id = request.session['cart_id']
        except:
            new_cart = Cart()
            new_cart.save()
            request.session['totalprice'] = 0
            request.session['cart_id'] = new_cart.id
            the_id = new_cart.id
        cart = Cart.objects.get(id=the_id)
        pizza = Pizzas.objects.get(id=pizza_id)

        changed_pizza = {
            'crust': request.POST['crust'],
            'toppings': sorted(request.POST.getlist('toppings')),
            'sauceBase': request.POST['sauceBase'],
            'diameter': request.POST['diameter']
        }

        ingr = literal_eval(pizza.ingredients)
        ingr['toppings'] = sorted(ingr['toppings'])
        if ingr == changed_pizza:
            cart_item, created = CartItem.objects.get_or_create(cart=cart,
                                                                pizzas=pizza)
            cart_item.line_total = pizza.price
        else:
            cart_item, created = CartItem.objects.get_or_create(
                cart=cart, pizzas=pizza, changes=str(changed_pizza))
            price = 5
            for topping in changed_pizza['toppings']:
                if topping[:3] == 'TME':
                    elem = Meat.objects.get(id=topping).price
                elif topping[:3] == 'TMU':
                    elem = Mushrooms.objects.get(id=topping).price
                elif topping[:3] == 'TFR':
                    elem = Fruits.objects.get(id=topping).price
                elif topping[:3] == 'TFI':
                    elem = Fish.objects.get(id=topping).price
                elif topping[:2] == 'TV':
                    elem = Vegetables.objects.get(id=topping).price
                elif topping[:2] == 'TS':
                    elem = Sauce.objects.get(id=topping).price
                else:
                    elem = Cheese.objects.get(id=topping).price
                price += elem
            price += Diameter.objects.get(id=changed_pizza['diameter']).price
            cart_item.price_changed = round(price, 2)
            cart_item.line_total = cart_item.price_changed

        cart_item.quantity += 1

        request.session['totalprice'] += cart_item.line_total
        cart_item.save()

        return HttpResponseRedirect(reverse("home"))

    else:
        pizza = Pizzas.objects.get(id=pizza_id)
        initial_toppings = literal_eval(pizza.ingredients)['toppings']
        initial_crust = literal_eval(pizza.ingredients)['crust']
        initial_sauceBase = literal_eval(pizza.ingredients)['sauceBase']
        initial_diameter = literal_eval(pizza.ingredients)['diameter']

        cheeses = Cheese.objects.all()
        crusts = Crust.objects.all()
        diameters = Diameter.objects.all()
        fish = Fish.objects.all()
        fruits = Fruits.objects.all()
        meats = Meat.objects.all()
        mushrooms = Mushrooms.objects.all()
        sauces = Sauce.objects.all()
        sauceBases = Saucebase.objects.all()
        vegetables = Vegetables.objects.all()

        new_toppings = list(
            itertools.zip_longest(cheeses, fish, fruits, meats, mushrooms,
                                  sauces, vegetables))

        context = {
            'pizza_id': pizza_id,
            'toppings': new_toppings,
            'crusts': crusts,
            'diameters': diameters,
            'sauceBases': sauceBases,
            'initial_toppings': initial_toppings,
            'initial_crust': initial_crust,
            'initial_sauceBase': initial_sauceBase,
            'initial_diameter': initial_diameter,
        }
        template = 'pizzaApp/edit.html'
        return render(request, template, context)
Exemple #33
0
    def get_object(self, *args, **kwargs):
        self.request.session.set_expiry(0)
        cart_id = self.request.session.get("cart_id")
        if cart_id is not None:
            cart = Cart.objects.get(id=cart_id)
            if self.request.user.is_authenticated():
                cart.user = self.request.user
                cart.save()
            return cart

        if not self.request.user.is_authenticated():
            cart = Cart(subtotal=0.00)
            cart.save()
            cart_id = cart.id
            self.request.session["cart_id"] = cart_id
        else:
            cart = Cart.objects.filter(user=self.request.user)
            if cart.count() >= 1:
                cart = cart.first()
            else:
                cart = Cart(subtotal=0.00, user=self.request.user)
                cart.save()
            cart_id = cart.id
            self.request.session["cart_id"] = cart_id
            cart.save()
        return cart
Exemple #34
0
 def remove_applied_coupon(cls, code: str, cart: Cart) -> None:
     qs = AppliedCoupon.objects.filter(coupon__code=code, cart=cart)
     if qs.exists():
         applied_coupon = qs.first()
         applied_coupon.delete()
         cart.update_totals()
Exemple #35
0
 def apply_coupon(cls, code: str, cart: Cart) -> Optional[Cart]:
     applied_coupon = AppliedCouponCreator(code=code, cart=cart)()
     cart.update_totals()
     return applied_coupon
Exemple #36
0
def add_to_cart(request, slug):
    request.session.set_expiry(120000)

    try:
        the_id = request.session['cart_id']
    except:
        new_cart = Cart()
        new_cart.save()
        request.session['cart_id'] = new_cart.id
        the_id = new_cart.id
    cart = Cart.objects.get(id=the_id)
    try:
        product = Product.objects.get(slug=slug)
    except Product.DoesNotExist:
        pass
    except:
        pass

    product_var = []  #product variation

    if request.method == 'POST':
        qty = request.POST['qty']
        for item in request.POST:
            key = item
            val = request.POST[key]
            try:
                v = Variation.objects.get(product=product,
                                          category__iexact=key,
                                          title__iexact=val)
                product_var.append(v)
                print(v)
            except:
                pass
        cart_item = CartItem.objects.create(cart=cart, product=product)
        if len(product_var) > 0:
            cart_item.variations.add(*product_var)
        cart_item.quantity = qty
        cart_item.save()
        new_total = 0.00
        for item in cart.cartitem_set.all():
            line_total = float(item.product.price) * item.quantity
            new_total += line_total
        request.session['items_total'] = cart.cartitem_set.count()
        print(cart.cartitem_set.count())
        cart_item.line_total = line_total
        print(cart_item.line_total)
        cart_item.save()

        try:
            the_id = request.session['cart_id']
            if the_id:
                cart = Cart.objects.get(id=the_id)
                print(cart)
                print('now it works')

        except:
            the_id = None
            return redirect(reverse('cart'))
        try:
            new_order = Order.objects.get(cart=cart)
        except Order.DoesNotExist:
            new_order = Order()
            new_order.cart = cart
            new_order.user = request.user
            new_order.order_id = id_generator()
            new_order.save()
        except:
            #work on some error message
            message.warning(request, 'You do not have an active order.')
            return redirect(reverse('cart'))
        #assign address
        #run credit card
        if new_order.status == 'Finished':
            del request.session['cart_id']
            del request.session['items_total']
            return redirect(reverse('cart'))

        return redirect(reverse('cart'))

    return redirect(reverse('cart'))