python-3.x - 更新数量和更新购物车 Django
问题描述
添加购物车
def add_to_cart_view(request,pk):
products=models.Product.objects.all()
#for cart counter, fetching products ids added by customer from cookies
if 'product_ids' in request.COOKIES:
product_ids = request.COOKIES['product_ids']
counter=product_ids.split('|')
product_count_in_cart=len(set(counter))
else:
product_count_in_cart=1
response = render(request, 'ecom/index.html',{'products':products,'product_count_in_cart':product_count_in_cart})
#adding product id to cookies
if 'product_ids' in request.COOKIES:
product_ids = request.COOKIES['product_ids']
if product_ids=="":
product_ids=str(pk)
else:
product_ids=product_ids+"|"+str(pk)
response.set_cookie('product_ids', product_ids)
else:
response.set_cookie('product_ids', pk)
product=models.Product.objects.get(id=pk)
messages.info(request, product.name + ' added to cart successfully!')
return response
结帐前查看购物车
def cart_view(request):
#for cart counter
if 'product_ids' in request.COOKIES:
product_ids = request.COOKIES['product_ids']
counter=product_ids.split('|')
product_count_in_cart=len(set(counter))
else:
product_count_in_cart=0
# fetching product details from db whose id is present in cookie
products=None
total=0
if 'product_ids' in request.COOKIES:
product_ids = request.COOKIES['product_ids']
if product_ids != "":
product_id_in_cart=product_ids.split('|')
products=models.Product.objects.all().filter(id__in = product_id_in_cart)
#for total price shown in cart
for p in products:
total=total+p.price
return render(request,'ecom/cart.html',{'products':products,'total':total,'product_count_in_cart':product_count_in_cart})
产品型号
class Product(models.Model):
name=models.CharField(max_length=40)
product_image= models.ImageField(upload_to='product_image/',null=True,blank=True)
price = models.PositiveIntegerField()
description=models.CharField(max_length=40)
def __str__(self):
return self.name
我希望在购物车页面中有一个字段将采用“整数输入”并更新总价
展示购物车 查看图片
我多么想要
我是新手,正在尝试和学习,所以请帮我解决这个问题
我需要任何新模型或视图吗?
谢谢你
解决方案
按下“添加到购物车”按钮后,我有一个想法,重定向到带有产品表单的新页面以获取订购数量..像这样:
{% extends 'base.html' %}
{% load static %}
{% block content %}
<div style="text-align:center";>
<h2 style="color: darkcyan;font-family: monospace;font-size: 55px;">Add item to your cart</h2><br>
<form method="POST">
{% csrf_token %}
<h5 style="font-size: 20px;color: blueviolet;">{{ product.name }}</h5>
<input name="ordered_qty" min="1" max="{{ product.quantity }}" type="number" oninput="validity.valid||(value='');" required>
<br><br>
<button class="btn btn-primary" type="submit" name="add_item">Add item</button>
</form>
{% endblock content %}
然后添加您的视图以更新计数器和 cookie(以设置订购数量)并保存在 cookie 中
def add_to_cart_view(request, pk):
if request.method == 'POST':
# take ordered qty and product id to create cookie
ordered_quantity = int(request.POST.get('ordered_qty'))
# Update Counter
if 'product_ids' in request.COOKIES:
product_ids = request.COOKIES['product_ids']
product_ids = json.loads(product_ids)
products_list_ids = [k['id'] for k in product_ids]
# if pk of product exist in counter don't incremment counter
if pk in products_list_ids:
products_count_in_cart = len(set(products_list_ids))
# else : (new product in cart) increment counter
else:
products_count_in_cart = len(set(products_list_ids)) + 1
else:
products_count_in_cart = 1
# Back to home page
products = Product.objects.filter(quantity__gt=0)
response = render(request, 'home.html', {'products': products, "products_count_in_cart": products_count_in_cart})
# Update Cookie by adding product id and qty
if 'product_ids' in request.COOKIES:
product_ids = request.COOKIES['product_ids']
products_list = json.loads(product_ids)
products_ids_list = [i['id'] for i in products_list ]
if pk not in products_ids_list:
products_list.append({'id': pk, 'ordered_qty': ordered_quantity})
response.set_cookie('product_ids', json.dumps(products_list))
else:
response.set_cookie('product_ids', json.dumps([{'id': pk, 'ordered_qty': ordered_quantity}]))
return response
else:
product = Product.objects.get(id=pk)
return render(request, 'add_item_to_cart.html', {'product': product})
最后,您可以在任何地方查看订购数量..这是我的解决方案,我在我的项目中应用了..效果很好另一个想法:搜索如何在您的主页中添加子模板以添加订购数量..
推荐阅读
- ios - NSLayoutConstraint - 两项,一行,间距优先
- android - 如何在改造 2 上发布整个数据库
- xamarin.forms - 未应用 CornerRadius
- r - 在 R dplyr 中按组将多列转换为相对频率
- apache-spark - 在 PySpark Structured Streaming 中为多个输出流使用单个流数据帧
- c - 从C中的void函数返回一个值
- javascript - addClass() 仅指向子元素(而不是嵌套元素)
- c - realloc 在第二次调用时失败
- python - 弹出索引超出范围python
- php - 如何从 MySQL 中获取值以选择/选项标签