Skip to content

Instantly share code, notes, and snippets.

@LowerDeez
Last active March 2, 2024 08:32
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LowerDeez/0719b2dcd0abdf1eb9b3ecc03655ed47 to your computer and use it in GitHub Desktop.
Save LowerDeez/0719b2dcd0abdf1eb9b3ecc03655ed47 to your computer and use it in GitHub Desktop.
Django. Simple Cart app for basic shop.
<div class="cart">
{% with total_items=cart|length %}
{% if cart|length > 0 %}
Ваша корзина:
<a href="{% url "cart:CartDetail" %}">
{{ total_items }} тов. {{ cart.get_total_price }} руб.
</a>
{% else %}
Корзина пустая
{% endif %}
{% endwith %}
</div>
# создадим внутри директории cart файл cart.py и заполним его следующим:
from decimal import Decimal
from django.conf import settings
from shop.models import Product
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
# Добавление товар в корзину пользователя
# или обновление количества товаров
def add(self, product, quantity=1, update_quantity=False):
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[settings.CART_SESSION_ID] = self.cart
# Указываем, что сессия изменена
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 __iter__(self):
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):
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):
del self.session[settings.CART_SESSION_ID]
self.session.modified = True
from .cart import Cart
def cart(request):
return {'cart': Cart(request)}
# Подключим этот файл в settings.py в переменной TEMPLATES:
....
'django.contrib.messages.context_processors.messages',
'cart.context_processors.cart'
{% extends "shop/base.html" %}
{% block title %}
Ваша корзина товаров
{% endblock %}
{% block content %}
<h1>Ваша корзина товаров</h1>
<table class="cart">
<thead>
<tr>
<th>Изображение</th>
<th>Продукт</th>
<th>Количество</th>
<th>Удалить</th>
<th>Полная цена</th>
<th>Цена</th>
</tr>
</thead>
<tbody>
{% for item in cart %}
{% with product=item.product %}
<tr>
<td>
<a href="{{ product.get_absolute_url }}">
<img src="{{ product.image.url }}" alt="" />
</a>
</td>
<td>{{ product.name }}</td>
<td>
<form action="{% url "cart:CartAdd" product.id %}" method="post" class="add">
{{ item.update_quantity_form.quantity }}
{{ item.update_quantity_form.update }}
{% csrf_token %}
<input type="submit" value="Обновить">
</form>
</td>
<td><a href="{% url "cart:CartRemove" product.id %}">Удалить</a></td>
<td class="num">{{ item.price }} руб.</td>
<td class="num">{{ item.total_price }} руб.</td>
</tr>
{% endwith %}
{% endfor %}
<tr class="total">
<td>Total</td>
<td colspan="4"></td>
<td class="num">{{ cart.get_total_price }} руб.</td>
</tr>
</tbody>
</table>
<p class="text-right">
<a href="{% url "shop:ProductList"%}" class="btn">Продолжить Шопинг</a>
<a href="#">Оформить заказ</a>
</p>
{% endblock %}
from django import forms
PRODUCT_QUANTITY_CHOICES = [(i, str(i)) for i in range(1, 21)]
class CartAddProductForm(forms.Form):
quantity = forms.TypedChoiceField(choices=PRODUCT_QUANTITY_CHOICES, coerce=int)
update = forms.BooleanField(required=False, initial=False, widget=forms.HiddenInput)
CART_SESSION_ID = 'cart'
# После установки идентификатора сессии, мы должны создать новое приложение под названием сart:
# $ python manage.py startapp cart
# Теперь надо добавить его в INSTALLED_APPS, чтобы Django мог использовать его
....
<p class="price">{{ product.price }} руб.</p>
<form action="{% url "cart:CartAdd" product.id %}" method="post">
{{ cart_product_form }}
{% csrf_token %}
<input type="submit" value="Добавить в корзину">
</form>
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.CartDetail, name='CartDetail'),
url(r'^remove/(?P<product_id>\d+)/$', views.CartRemove, name='CartRemove'),
url(r'^add/(?P<product_id>\d+)/$', views.CartAdd, name='CartAdd'),
]
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 CartAdd(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'])
return redirect('cart:CartDetail')
def CartRemove(request, product_id):
cart = Cart(request)
product = get_object_or_404(Product, id=product_id)
cart.remove(product)
return redirect('cart:CartDetail')
def CartDetail(request):
cart = Cart(request)
for item in cart:
item['update_quantity_form'] = CartAddProductForm(
initial={
'quantity': item['quantity'],
'update': True
})
return render(request, 'cart/detail.html', {'cart': cart})
@Wet-panties
Copy link

r u forgot models.py

@slovib
Copy link

slovib commented Mar 1, 2024

are y forgot models bro

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment