Last active
November 4, 2020 07:50
-
-
Save zeraien/839950a1491a1859f4577885f5f0886b to your computer and use it in GitHub Desktop.
django super simple cart
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from django.shortcuts import redirect | |
| from django.shortcuts import get_object_or_404 | |
| from django.views.decorators.http import require_http_methods | |
| def _get_products_in_cart(request): | |
| """ | |
| Returns an array of dicts with the `product` and `quantity` | |
| as the two keys | |
| """ | |
| cart = request.session.get('cart', {}) | |
| products = Product.objects.in_bulk(cart.keys()) | |
| return [ | |
| { | |
| "product": products[product_id], | |
| "quantity": quantity | |
| } for product_id, quantity in cart.items() | |
| ] | |
| def cart_page(request): | |
| products = _get_products_in_cart(request) | |
| # you can access product.quantity to see how many products are in the cart | |
| c = { | |
| "cart_products": products | |
| } | |
| return render(request, "cart.html", context=c) | |
| @require_http_methods(["POST"]) | |
| def add_to_cart(request): | |
| product_id = request.POST.get("product_id") | |
| quantity = request.POST.get("quantity",1) | |
| product = get_object_or_404(Product, pk=product_id) | |
| cart = request.session.get('cart', {}) | |
| cart[product.pk] = quantity | |
| request.session['cart'] = cart | |
| return redirect(...) # redirect back to previous page or product page |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment