Beispiel #1
0
def confirmation(request):
    if request.method == "POST":
        #protection against refreshing or posts with empty cart
        if len(request.session['cart']) == 0:
            context = generate_cart_context(request)
            context[
                'alert_message'] = "You have to order something first before you can get a confirmation. 🤔"
            return render(request, 'cart.html', context=context)

        form = CheckoutForm(request.POST)
        # Check if the form is valid:
        if form.is_valid():
            order_obj = Order(
                first_name=form.cleaned_data['first_name'],
                last_name=form.cleaned_data['last_name'],
                student_id=form.cleaned_data['student_id'],
                email=form.cleaned_data['email'],
                phone=form.cleaned_data['phone'],
                special_instructions=form.cleaned_data['special_instructions'],
                grand_total=0.0)
            order_obj.save()

            grand_total = 0
            for cart_id, cart_item in request.session['cart'].items():
                product_obj = Product.objects.get(id=cart_item['product_id'])
                material_obj = Material.objects.get(id=cart_item['material'])
                price = int(cart_item['quantity']) * product_obj.price
                grand_total += price

                product_instance = ProductInstance(product=product_obj,
                                                   material=material_obj,
                                                   quantity=int(
                                                       cart_item['quantity']),
                                                   total_price=price,
                                                   order=order_obj)
                product_instance.save()
            order_obj.grand_total = grand_total

            context = generate_cart_context(request)
            context["order"] = order_obj

            send_confirmation_email(context, form.cleaned_data['email'])

            request.session['cart'] = {}
            return render(request, 'confirmation.html', context=context)
    else:
        context = generate_cart_context(request)
        context[
            'alert_message'] = "You have to order something first before you can get a confirmation. 🤔"
        return render(request, 'cart.html', context=context)