def post(request): order_form = OrderForm(request.POST) cart = Cart(request) if order_form.is_valid(): try: new_order = order_form.save(commit=False) new_order.total_price = cart.get_total_price() new_order.save() for item in cart: product = Product.objects.get(id=int(item['product_id'])) OrderItem.objects.create(order=new_order, product=product, price=item['price'], quantity=item['quantity'], total_price=item['cost'], bar_type=item['bar_type']) current_site = get_current_site(request) mail_subject = 'Новый заказ на сайте: ' + current_site.domain message = render_to_string('email_messages/order_message.html', { 'domain': current_site.domain, 'order': new_order, }) to_email = MailToString.objects.first().email email = EmailMessage(mail_subject, message, to=[to_email]) email.send() cart.clear() status = 1 except Exception as e: print(e) status = 0 else: status = 0 context = { 'status': status, } return JsonResponse(context)
def post(self, request): order_form = OrderForm(request.POST) pay_type = request.POST.get('pay-type') cart = Cart(request) user = request.user if order_form.is_valid(): order = order_form.save() order_items = [] for item in cart: offer = item['offer'] if item['has_present']: order_item = OrderItem(order=order, offer=offer, price=item['price'], discount=item['price'], total_price_with_sale=0, quantity=1) order_items.append(order_item) if item['quantity'] - 1: order_item = OrderItem( order=order, offer=offer, price=item['price'], discount=item['cost'] - item['cost_with_sale'] - item['price'], total_price_with_sale=item['cost_with_sale'], quantity=item['quantity'] - 1) order_items.append(order_item) else: order_item = OrderItem( order=order, offer=offer, price=item['price'], discount=item['cost'] - item['cost_with_sale'], total_price_with_sale=item['cost_with_sale'], quantity=item['quantity']) order_items.append(order_item) offer.stock -= int(item['quantity']) order.delivery_price = int(cart.delivery['price']) order.total_price = cart.offers_price + int(cart.delivery['price']) order.total_price_with_sale = cart.get_total_price() order.user = user if user.is_authenticated else None order.pay_type = pay_type order.save() OrderItem.objects.bulk_create(order_items) Offer.objects.bulk_update(cart.offers, ['stock']) if pay_type == 'online': form_url = order_pay_response(request, order) elif pay_type == 'credit': form_url = order_pay_credit(request, order) return redirect(form_url) else: messages.error(request, 'Заполните все поля правильно') context = { 'order_form': order_form, } return render(request, 'orders/cart.html', context)