0
我要創造我的購物車Django的shop.i啓動新的應用程序命名爲購物車和新文件添加到這個應用程序cart.py。在這個文件中,我創建了類Cart,並添加了一些功能。 這是cart.pyDjango的cart_add 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})
和last is th detail.html in cart app:
{% 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大小的工作很好,並顯示我的產品在cart/detail.html沒有大小,但我需要它。我如何解決它?
我做到這一點,不要」 t工作 – KeepItSick
另外,我認爲你已經混合了字段'size'和'sz'的用途。在CartAddProductForm中,您應該將字段名稱從'sz'更改爲'size',並將初始更改爲某種有效的大小(在SIZE_CHOICES中指定)。 – doggra