...
@require_POST
def cart_add(request, product_id, product_slug):
cart = Cart(request)
product = get_object_or_404(Product, id=product_id, slug = product_slug)
form = CartAddProductForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
cart.add(product=product,
quantity=cd['quantity'],
update_quantity=cd['update'])
return redirect('cart:cart_detail' )
def cart_remove(request, product_id, product_slug):
cart = Cart(request)
product = get_object_or_404(Product, id=product_id, slug = product_slug)
cart.remove(product)
return redirect('cart:cart_detail')
def cart_detail(request,product_id, product_slug,category_slug=None):
product = get_object_or_404(Product, id=product_id, slug = product_slug)
category = None
categories = Category.objects.all()
if category_slug:
category = get_object_or_404(Category, slug=category_slug)
cart = Cart(request)
for item in cart:
item['update_quantity_form'] = CartAddProductForm(initial={'quantity': item['quantity'],
'update': True})
coupon_apply_form = CouponApplyForm()
return render(request, 'cart/detail.html', {'cart': cart,'category': category,'categories': categories,'coupon_apply_form':coupon_apply_form, 'product': product},id=product_id, slug = product_slug)
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.cart_detail, name='cart_detail'),
url(r'^add/(?P<product_id>\d+)(?P<product_slug>[-\w]+)/$', views.cart_add, name='cart_add'),
url(r'^remove/(?P<product_id>\d+)/$', views.cart_remove, name='cart_remove'),
]
{% extends "app/layout.html" %}
{% load static %}
{% block content %}
<table class="table-shopping-cart">
<tr class="table_head">
<th class="column-1">Продукт</th>
<th class="column-2"></th>
<th class="column-3">Цена за шт</th>
<th class="column-4">Кол-во</th>
<th class="column-5">Итог</th>
<th class="column-6">Удалить</th>
</tr>
{% for item in cart %}
{% with product=item.product %}
<tr class="table_row">
<td class="column-1">
<div class="how-itemcart1">
<a href="{{ product.get_absolute_url }}">
<img src="{% if product.image1 %}{{ product.image1.url }}{% else %}{% static 'content/no_image.png' %}{% endif %}">
</a>
</div>
</td>
<td class="column-2">{{ product.name }}</td>
<td class="column-3">{{ item.price }} руб.</td>
<td class="column-4">
{{item.quantity}}
</td>
<td class="column-5">{{ item.total_price }} руб. </td>
<td class="column-6" ><a href="{% url 'cart:cart_remove' product.id product.slug %}">Удалить</a></td>
</tr>
{% endwith %}
{% endfor %}
{% endblock %}
from decimal import Decimal
import django
from django.conf import settings
from shop.models import Product
from coupons.models import Coupon
class Cart(object):
def __init__(self, request):
self.session = request.session
cart = self.session.get(settings.CART_SESSION_ID)
if not cart:
# сохраняем ПУСТУЮ корзину в сессии
cart = self.session[settings.CART_SESSION_ID] = {}
self.cart = cart
self.coupon_id = self.session.get('coupon_id')
def __iter__(self):
product_ids = self.cart.keys()
# получаем товары и добавляем их в корзину
products = Product.objects.filter(id__in=product_ids)
cart = self.cart.copy()
for product in products:
cart[str(product.id)]['product'] = product
for item in cart.values():
item['price'] = Decimal(item['price'])
item['total_price'] = item['price'] * item['quantity']
yield item
def __len__(self):
return sum(item['quantity'] for item in self.cart.values())
def add(self, product, quantity=1, update_quantity=True): # 22 10 2020
Добавляем товар в корзину или обновляем его количество.
product_id = str(product.id)
if product_id not in self.cart:
self.cart[product_id] = {'quantity': 0,
'price': str(product.price)}
if update_quantity:
self.cart[product_id]['quantity'] = quantity
else:
self.cart[product_id]['quantity'] += quantity
self.save()
def save(self):
# сохраняем товар
self.session.modified = True
def remove(self, product):
product_id = str(product.id)
if product_id in self.cart:
del self.cart[product_id]
self.save()
def get_total_price(self):
# получаем общую стоимость
return sum(Decimal(item['price']) * item['quantity'] for item in self.cart.values())
@property
def coupon(self):
if self.coupon_id:
return Coupon.objects.get(id=self.coupon_id)
return None
def get_discount(self):
if self.coupon:
return (self.coupon.discount / Decimal('100')) * self.get_total_price()
return Decimal('0')
def get_total_price_after_discount(self):
return self.get_total_price() - self.get_discount()
def clear(self):
del self.session[settings.CART_SESSION_ID]
self.save()
urlpatterns = [
...
url(r'^orders/', include('shop.urls', namespace='shop1')),
url(r'^goods/', include('shop.urls', namespace='shop')),
url(r'^cart/', include('cart.urls', namespace='cart')),
url(r'^contact$', app.views.contact, name='contact'),
...
<b>Приложение shop</b>
<spoiler title="shop/views.py"><code>
...
from django.shortcuts import render, get_object_or_404,redirect
def product_list(request, category_slug=None):
category = None
categories = Category.objects.all()
products = Product.objects.filter(available=True)
if category_slug:
category = get_object_or_404(Category, slug=category_slug)
products = products.filter(category=category)
return render(request,
'shop/product/list.html',
{'category': category,
'categories': categories,
'products': products})
def product_detail(request, id, slug,category_slug=None):
category = None
categories = Category.objects.all()
if category_slug:
category = get_object_or_404(Category, slug=category_slug)
product = get_object_or_404(Product,
id=id,
slug=slug,
available=True)
cart_product_form = CartAddProductForm()
assert isinstance(request, HttpRequest)
return render(request, 'shop/product/detail.html', {'reviews':reviews,'product': product,'form':form,'cart_product_form': cart_product_form,'category': category,'categories': categories,})
def order_create(request,product_id,product_slug):
cart = Cart(request)
product = get_object_or_404(Product,
id=product_id,
slug=product_slug,
)
if request.method == 'POST':
form = OrderCreateForm(request.POST)
if form.is_valid():
order = form.save(commit=False)
order.nickname = request.user
order.product = product
order.save()
for item in cart:
Order.objects.create(
product=item['product'],
price=item['price'],
quantity=item['quantity'])
# очистка корзины
cart.clear()
return render(request, 'orders/order/created.html',
{'order': order})
else:
form = OrderCreateForm()
return render(request, 'orders/order/create.html',
{'cart': cart, 'form': form, 'product':product})
</code></spoiler>
<img src="https://habrastorage.org/webt/5f/ce/15/5fce159050df8277280844.png" alt="image"/>
<img src="https://habrastorage.org/webt/5f/ce/16/5fce1649b88ec058912027.png" alt="image"/>
<b>Кажется нужно прописать что-то в cart/detil.html, но что?</b>