def cart_detail(request): cart = Cart(request) delivery_form = None if request.user.is_authenticated: delivery_form = ChooseDeliveryType(request.POST) if delivery_form.is_valid(): choice = request.POST.copy() choice = int(choice.get('delivery_type')) delivery = Delivery(cart.get_total_price(), FREE_DELIVERY_PRICE) delivery.set_delivery(choice) discount = cart.get_discount() new_order = Order(user=request.user, is_confirmed=False, delivery_price=delivery.get_delivery_price(), delivery_type=delivery.delivery_name, expiration_date=timezone.now() + datetime.timedelta(days=7), discount=discount) new_order.save() order_id = new_order.id return redirect('cart:choose_address', order_id) coupon_apply_form = CouponApplyForm() return render( request, 'cart/checkout.html', { 'cart': cart, 'delivery_form': delivery_form, 'free_delivery_price': FREE_DELIVERY_PRICE, 'coupon_apply_form': coupon_apply_form })
def cart(request): if request.method == "POST": items_json = request.POST.get('itemsJson', '') name = request.POST.get('name', '') email = request.POST.get('email', '') address = request.POST.get('address', '') city = request.POST.get('city', '') state = request.POST.get('state', '') zip_code = request.POST.get('zip_code', '') phone = request.POST.get('phone', '') order = Order(items_json=items_json, name=name, email=email, address=address, city=city, state=state, zip_code=zip_code, phone=phone) order.save() update = OrderUpdate(order_id=order.order_id, update_desc="The order has been placed") update.save() id = order.order_id return render(request, "cart/index.html") return render(request, "cart/cart.html")
def index(request): if request.method == 'POST': form = OrderFormSimple(request.POST) # A form bound to the POST data # All validation rules pass if form.is_valid(): # parsing products items order_items = json.loads(form.cleaned_data['items']) city_item = json.loads(form.cleaned_data['city']) office_item = json.loads(form.cleaned_data['office']) if settings.DEBUG: print " === Order data === " pprint(form.cleaned_data) print " === Order items === " pprint(order_items) # saving order order = Order( shipping_name=form.cleaned_data['name'], billing_name=form.cleaned_data['name'], shipping_address='%s (%s)' % (office_item['address'], office_item['name']), billing_address='%s (%s)' % (office_item['address'], office_item['name']), shipping_city='%s (%s)' % (city_item['name'], city_item['region']), billing_city='%s (%s)' % (city_item['name'], city_item['region']), email=form.cleaned_data['email'], phone=form.cleaned_data['phone'], ip_address=get_client_ip(request) ) order.save() # saving order products for item in order_items: order_item = OrderItem( product=Product.objects.get(pk=item['product']), quantity=int(item['quantity']), price=Product.objects.get(pk=item['product']).price, order=order ).save() return HttpResponseRedirect('/cart/thanks/' + str(order.pk)) # Redirect after POST else: form = OrderFormSimple() # by default Standard return render_to_response( 'cart/index.html', { 'category_list': Category.active.all(), 'form': form }, context_instance=RequestContext(request))
def get_current_order(customer, create_if_needed=False): print "Gettting current order for user %s" % str(customer.user) current_order = Order.objects.filter( status=1, customer=customer).order_by("created_on").last() if not current_order and create_if_needed: print "No current order. %s" % str(customer.user) current_order = Order(customer=customer) current_order.save() print "Created order. %s" % str(customer.user) return current_order
def test_default_values(self): """ test that new Order instance sets it's paid and shipped boolean values to false """ user = User(username="******") order = Order(id=42, date_ordered='2019-11-10', customer=user) self.assertEqual(order.paid, False) self.assertEqual(order.shipped, False)
def test_order_id_on_order_item(self): product = Product(title="Test Product") order = Order(id=42, full_name="John Wayne") order_item = OrderItem(order=order, product=product, quantity=3) self.assertEqual(order_item.order.id, 42)
def test_default_values(self): user = User(username="******") order = Order(id=42, date_ordered='2020-07-06', customer=user) self.assertEqual(order.paid, False) self.assertEqual(order.shipped, False)
def test_product_id_in_order_item(self): product = Product(id=99, title="Test Product") order = Order(id=42, full_name="John Wayne") order_item = OrderItem(order=order, product=product, quantity=3) self.assertEqual(order_item.product.id, 99)
def test_order_id_on_order_item(self): """ Test that OrderItem model correctly stores the Id of is related Order instance """ product = Product(title="Test Mouse") order = Order(id=42, full_name="Arthur Dent") order_item = OrderItem(order=order, product=product, quantity=3) self.assertEqual(order_item.order.id, 42)
def test_string_representation(self): user = User(username="******") order = Order(id=42, date_ordered='2020-07-06', customer=user) expected_result = '42-2020-07-06-Longmire' self.assertEqual(str(order), expected_result)
def test_product_id_in_order_item(self): """ Test that OrderItem model correctly stores the id of its related Product instance """ product = Product(id=99, title="Test Mouse") order = Order(id=42, full_name="Arthur Dent") order_item = OrderItem(order=order, product=product, quantity=3) self.assertEqual(order_item.product.id, 99)
def confirm(request): # create the order for the orderID - userID table newrow = Order(user=request.user, orderDate=timezone.now(), firstName=request.session["contactinfo"]["name"], lastName=request.session["contactinfo"]["name"], streetName=request.session["contactinfo"]["street_name"], houseNumber=request.session["contactinfo"]["house_number"], zipCode=request.session["contactinfo"]["zip"], city=request.session["contactinfo"]["city"], country=request.session["contactinfo"]["country"]) newrow.save() order_id = newrow.id #create an OrderItem with all the information for an order cart_list = Cart.objects.filter(user=request.user) # list of Carts order = Order.objects.get(id=order_id) for cart in cart_list: newrow = OrderItem( order=order, product=cart.product, quantity=cart.quantity) # how to do quantity big brain plz newrow.save() #clear the cart for data in cart_list: data.delete() #clear the user contact and payment data from sessions request.session.pop('contactinfo') request.session.pop('paymentinfo') return render(request, 'checkout/confirm.html')
def __init__(self, data, request, cart=None): self.created_by_staff = False token = request.COOKIES.get('x-token', None) if token is not None: self.created_by_staff = True self._user = self.get_user(request) if cart is None: self._cart = self.get_cart(request) else: self._cart = cart self._location = self.get_location(request) self._customer = self.get_customer_data(data) self._delivery = self.get_delivery_data(data) self._payment = self.get_payment_data(data) self._cpa = self.get_cpa_data(data) self._store = self.get_store_data() self._sale = self.get_sale() self._total_price = self.get_total_price() self._client_notes = self.get_client_notes(data) self._source = self.get_source(data) self._instance = Order(cart=self._cart.data, user=self._user, location=self._location, customer=self._customer, delivery=self._delivery, payment=self._payment, cpa=self._cpa, store=self._store, source=self._source, client_notes=self._client_notes, sale=self._sale, total_price=self._total_price, created_by_staff=self.created_by_staff) self._instance.uuid = Order._generate_uuid() for i in range(100): self._instance.public_id = Order._generate_public_id() try: Order.objects.get(public_id=self._instance.public_id) except ObjectDoesNotExist: break
def test_string_representation(self): """ Test that model returns correctly formatted string """ user = User(username="******") order = Order(id=42, date_ordered='2019-11-10', customer=user) expected_result = '42-2019-11-10-Trillian' self.assertEqual(str(order), expected_result)
def test_string_representation(self): product = Product(title="Test Product") order = Order(full_name="John Wayne") order_item = OrderItem(order=order, product=product, quantity=3) expected_result = '3 x Test Product' self.assertEqual(str(order_item), expected_result)
def test_string_representation(self): """ Test that model returns correctly formatted string """ product = Product(title="Test Mouse") order = Order(full_name="Arthur Dent") order_item = OrderItem(order=order, product=product, quantity=3) expected_result = '3 x Test Mouse' self.assertEqual(str(order_item), expected_result)
def add(request): try: username = request.session['username'] item = request.POST.get('item') quantity = request.POST.get('quantity') if int(quantity) < 1: return render(request, 'eshop.html', {'msg': 'Cannot add to cart'}) qu = Product.objects.get(id=item) price = qu.price for i in Order.objects.all(): if i.p_id == qu and username == i.user_id: i.quantity = int(i.quantity) + int(quantity) i.save() return HttpResponseRedirect('/cart/') q = Order( user_id=username, o_date=datetime.datetime.now(), price=price, p_id=qu, quantity=quantity, images=qu.img, item=qu.product_name, ) qu=Ordered( user_id=username, o_date=datetime.datetime.now(), price=price, p_id=qu, quantity=quantity, images=qu.img, item=qu.product_name, ) q.save() qu.save() u=request.session['username'] print(u) return HttpResponseRedirect('/cart/') except KeyError: return render(request, 'login.html', {'msg': 'Please Login to Modify your Cart!'}) except ValueError: return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
def checkout_review(request, cid=None, pid=None): if request.user.customer.active_cart and cid and pid: contact_info = Contact_info.objects.get(pk=int(cid)) payment_info = Payment_info.objects.get(pk=int(pid)) if request.method == "POST" and contact_info and payment_info: if request.POST.get('create_order') == 'true': order = Order( cart=request.user.customer.active_cart, user=request.user, contact=contact_info, payment=payment_info, status='Unpaid') order.save() return redirect('checkout_confirm', oid=order.id) context = { 'contact_info': contact_info, 'payment_info': payment_info, 'cart': request.user.customer.active_cart, 'style': 'checkout.css' } return render(request, 'cart/checkout_review.html', context) else: raise Http404()
def purchase_activate(request, uidb64, token, oidb64): user = User.get_decrypted_object(uidb64) validated_token = account_activation_token.check_token(user, token) if not user and not validated_token: messages.error(request, 'Invalid activation link!') return redirect('login') else: user.activate() auth_login(request, user, backend='django.contrib.auth.backends.ModelBackend') # Log in user order = Order.get_decrypted_object(oidb64) if not order: messages.error(request, 'Unable to find purchase. Contact with administrator.') return redirect('index') else: order.update_status(Order.CONFIRMED) return redirect(reverse('summary', kwargs={'ref_code': order.ref_code, 'oidb64': oidb64, }))
def get_users_orders(orders): """get all users orders and place in list""" users_orders = [] for item in orders: orderitems = [] order_answer = item.answer_correct order_items = item.items.all() for ticket in order_items: order_item_current = OrderItem.objects.get(id=ticket.id) entries_per_order = [] if order_answer: entries = Entries.objects.filter( orderItem=order_item_current.id) for ent in entries: entries_per_order.append(ent.ticket_number) product_item = [ticket.product, ticket.quantity, entries_per_order] orderitems.append(product_item) order_to_add = [ item, Order.get_total(item), order_answer, [orderitems] ] users_orders.append(order_to_add) return users_orders
class OrderCreateSerializer(): def __init__(self, data, request, cart=None): self.created_by_staff = False token = request.COOKIES.get('x-token', None) if token is not None: self.created_by_staff = True self._user = self.get_user(request) if cart is None: self._cart = self.get_cart(request) else: self._cart = cart self._location = self.get_location(request) self._customer = self.get_customer_data(data) self._delivery = self.get_delivery_data(data) self._payment = self.get_payment_data(data) self._cpa = self.get_cpa_data(data) self._store = self.get_store_data() self._sale = self.get_sale() self._total_price = self.get_total_price() self._client_notes = self.get_client_notes(data) self._source = self.get_source(data) self._instance = Order(cart=self._cart.data, user=self._user, location=self._location, customer=self._customer, delivery=self._delivery, payment=self._payment, cpa=self._cpa, store=self._store, source=self._source, client_notes=self._client_notes, sale=self._sale, total_price=self._total_price, created_by_staff=self.created_by_staff) self._instance.uuid = Order._generate_uuid() for i in range(100): self._instance.public_id = Order._generate_public_id() try: Order.objects.get(public_id=self._instance.public_id) except ObjectDoesNotExist: break def get_cart(self, request): return Cart(request) def get_location(self, request): return { 'city': { 'name': request.location['name'], 'code': request.location['code'] } } def get_customer_data(self, data): return data.get('customer') def get_user(self, request): user = request.user if request.user.is_authenticated else None return user def get_delivery_data(self, data): return data.get('delivery') def get_payment_data(self, data): return data.get('payment') def get_cpa_data(self, data): if not self.created_by_staff: return data.get('cpa', {}) else: return {} def get_store_data(self): return {} def get_client_notes(self, data): return data.get('client_notes') def get_source(self, data): return data.get('source') def get_sale(self): promocode = self._cart.data.get('promocode') sale = self._cart.data.get('total_sale') return {'promocode': promocode, 'amount': sale} def get_total_price(self): return self._cart.data['total_price'] + self._delivery['price'] def validate(self): self._instance.full_clean() @property def is_valid(self): pass def save(self): self._cart.clear() self._instance.save() if not settings.DEBUG: sms_notify.delay(self._instance.public_id) return self._instance
def confirm(request): name = request.POST['name'] phone = request.POST['phone'] address = request.POST['address'] postcode = request.POST['postcode'] ids = request.POST['ids'] allow_sub_detail = request.POST['allow_sub_detail'] deliveryWindow = request.POST['time'] coupon = request.POST['coupon'] res = computeSummaryInternal(ids, coupon) price = res['sum'] tax = res['tax'] shipping = res['delivery'] discount = res['discount'] total = max( float(price) + float(tax) + float(shipping) - float(discount), 0) invoice = str(uuid.uuid4()) Order(name=name, address=address, phone=phone, postcode=postcode, items=ids, allow_sub_detail=allow_sub_detail, price=price, tax=tax, shipping=shipping, status='pending', delivery_window=deliveryWindow, time=datetime.now(), invoice=invoice).save() paypal_dict = { "business": PAYPAL_RECEIVER_EMAIL, "currency_code": "CAD", "amount": "%.2f" % total, "item_name": "fruitex order", "invoice": invoice, "notify_url": "http://%s/fruitex-magic-ipn/" % DOMAIN, "return_url": "http://%s/redir/?%s" % (DOMAIN, urlencode({"to": "/check_order?invoice=" + invoice})), "return": "http://%s/return_page/" % DOMAIN, "cancel_return": "http://i%s/redir/?to=/home" % DOMAIN, "custom": json.dumps({'coupon': coupon}) } # Create the instance. form = PayPalPaymentsForm(initial=paypal_dict) context = { 'name': name, 'ids': ids, 'phone': phone, 'address': address, 'postcode': postcode, 'phone': phone, 'price': price, 'tax': tax, 'delivery': shipping, 'delivery_window': deliveryWindow, 'invoice': invoice, 'form': form, 'discount': discount, 'total': round(total, 2), 'sandbox': DEBUG, 'allow_sub_detail': allow_sub_detail } return render_to_response("confirm.html", context)