我想在我的django-shop.i中创建购物车。启动名为购物车的新应用,并将新文件添加到此应用 cart.py 。在这个文件中我创建了类Cart并添加了一些功能。 这是cart.py
class Cart(object):
def __init__(self, request):
"""
Inicjaliazacja koszyka na zakupy.
"""
self.session = request.session
cart = self.session.get(settings.CART_SESSION_ID)
if not cart:
# pusty koszyk w sesji
cart = self.session[settings.CART_SESSION_ID] = {}
self.cart = cart
def add(self, product, quantity=1, update_quantity=False, size=None, upd_size=False):
"""
Dodanie produktu i zmiana ilości
"""
product_id = str(product.id)
if product_id not in self.cart:
self.cart[product_id] = {'quantity': 0,
'size': None,
'price': str(product.price)}
if update_quantity:
self.cart[product_id]['quantity'] = quantity
else:
self.cart[product_id]['quantity'] += quantity
if upd_size:
self.cart[product_id]['size'] = size
else:
self.cart[product_id]['size'] += size
self.save()
def save(self):
self.session[settings.CART_SESSION_ID] = self.cart
self.session.modified = True
def remove(self, product):
"""
Usunięcie produktów z koszyka
"""
product_id = str(product.id)
if product_id in self.cart:
del self.cart[product_id]
self.save()
def __iter__(self):
"""
Iteracja przez elementy na zakupy i pobranie z bazy danych
"""
product_ids = self.cart.keys()
products = Product.objects.filter(id__in=product_ids)
for product in products:
self.cart[str(product.id)]['product'] = product
for item in self.cart.values():
item['price'] = Decimal(item['price'])
item['total_price'] = item['price'] * item['quantity']
yield item
def __len__(self):
"""
Obliczanie liczby wszytskich elementów w koszyku.
"""
return sum(item['quantity'] for item in self.cart.values())
def get_total_price(self):
return sum(Decimal(item['price']) * item['quantity'] for item in self.cart.values())
def clear(self):
# usunięcie koszyka
del self.session[settings.CART_SESSION_ID]
self.session.modified = True
接下来我创建了文件(forms.py)并添加了这段代码:
from django import forms
PRODUCT_QUANTITY_CHOICES = [(i, str(i)) for i in range(1, 21)]
SIZE_CHOICES = (
('S', 'S'),
('M', 'M'),
('L', 'L'),
('XL', 'XL')
)
class CartAddProductForm(forms.Form):
quantity = forms.TypedChoiceField(
choices=PRODUCT_QUANTITY_CHOICES,
coerce=int)
update = forms.BooleanField(required=False,
initial=False,
widget=forms.HiddenInput)
sz = forms.MultipleChoiceField(
required=True,
widget=forms.RadioSelect,
choices=SIZE_CHOICES,
initial=False)
我的下一步是创建视图
from django.shortcuts import render, redirect, get_object_or_404
from django.views.decorators.http import require_POST
from shop.models import Product
from .cart import Cart
from .forms import CartAddProductForm
@require_POST
def cart_add(request, product_id):
cart = Cart(request)
product = get_object_or_404(Product, id=product_id)
form = CartAddProductForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
cart.add(product=product,
quantity=cd['quantity'],
update_quantity=cd['update'],
size=cd['size'],
upd_size=['sz'])
return redirect('cart:cart_detail')
def cart_remove(request, product_id):
cart = Cart(request)
product = get_object_or_404(Product, id=product_id)
cart.remove(product)
return redirect('cart:cart_detail')
def cart_detail(request):
cart = Cart(request)
for item in cart:
item['update_quantity_form'] = CartAddProductForm(
initial={'quantity': item['quantity'],
'update': True,
'size': item['size'],
'sz': True}
)
return render(request,
'cart/detail.html',
{'cart': cart})
,最后一个是购物车应用中的detail.html:
{% extends "shop/base.html" %}
{% load static %}
{% block title %}{{ product.name }}{% endblock %}
{% block content %}
<div class="container-fluid">
<div class="row">
{% for item in cart %}
{% with product=item.product %}
<div class="col-md-2">
<a href="{{ product.get_absolute_url }}">
<img src="{{ product.image_url }}" class="img-responsive">
</a>
</div>
{{product.name}}
<form action="{% url 'cart:cart_add' product.id %}" method="post">
{{ item.update_quantity_form.quantity }}
{{ item.update_quantity_form.update }}
<input type="submit" value="Zmień">
{% csrf_token %}
</form>
{{ item.quantity }}
{{ item.size }}
<a href="{% url 'cart:cart_remove' product.id%}">Usuń</a>
{{item.price}}
{{item.total_price}}
{% endwith %}
{% endfor %}
{{cart.get_total_price}}
<a href="{% url 'orders:order_create' %}">
Do kasy
</a>
</div>
</div>
{% endblock %}
我在poduct detail.html中添加表单以在购物车中添加产品。
出了什么问题? 当我点击添加到购物车将我移动到cart / detail.html但没有显示。 当我删除大小适合工作的evrything并向我展示购物车/ detail.html没有尺寸的产品但我需要它。我怎么解决它?
答案 0 :(得分:0)
你的观点中有错字。
应该有cd ['sz'],而不是['sz']
现在是:
<div class="posts">
<div class="post">
<div class="single-piece">
<a>
<img src="https://images-na.ssl-images-amazon.com/images/G/01/img15/pet-products/small-tiles/23695_pets_vertical_store_dogs_small_tile_8._CB312176604_.jpg">
</a>
</div>
</div>
<div class="post">
</div>
<div class="post">
</div>
</div>
应该是
if form.is_valid():
cd = form.cleaned_data
cart.add(product=product,
quantity=cd['quantity'],
update_quantity=cd['update'],
size=cd['size'],
upd_size=['sz'])
return redirect('cart:cart_detail')