0

Проблема в следующем: есть проект на Django, в котором реализована корзина. Если добавлять в неё разные товары, то все работает отлично, и из самой корзины можно изменить количество товара, но, если из карточки товара нажать ещё раз кнопку добавить в корзину, то создастся дубль товара в корзине, а я хочу реализовать, чтобы увеличивалось количество товара в корзине. Код прилагаю: views.py

@login_required
def add_to_cart(request):
    user = request.user
    product_id = request.GET.get('prod_id')
    product = Product.objects.get(id=product_id)
    Cart(user=user, product=product).save()
    return redirect('/cart')


@login_required
def show_cart(request):
    user = request.user
    cart = Cart.objects.filter(user=user)
    amount = 0
    for p in cart:
        value = p.quantity * p.product.discounted_price
        amount= amount + value
    totalamount = amount + 150
    totalitem = 0
    wishitem = 0
    if request.user.is_authenticated:
        totalitem = len(Cart.objects.filter(user=request.user))
        wishitem = len(Wishlist.objects.filter(user=request.user))
    return render(request, 'application/addtocart.html', locals())```

models.py

class Cart(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    quantity = models.PositiveIntegerField(default=1)
    @property
    def total_cost(self):
        return quantity * self.product.discounted_price```

addtocart.html

{% extends 'application/base.html' %}
{% load static %}
{% block title %}Корзина{% endblock title %}
{% block main-content %}
<div class="container my-5">
  <div class="row">
    {% if cart %}
    <h1 class="text-center mb-5">Корзина Покупок</h1>
    <div class="col-sm-8">
      <div class="card">
        <div class="card-body">
          <h3>Корзина</h3>
          {% for item in cart %}
          <div class="row">
            <div class="col-sm-3 text-center align-self-center"><img src="{{item.product.product_image.url}}" alt=""
              srcset="" class="img-fluid img-thumbnail shadow-sm" height="150" width="150"> </div>
            <div class="col-sm-9">
              <div>
                <h5>{{item.product.title}}</h5>
                <p class="mb-2 text-muted small">{{item.product.descriptions}}</p>
                <div class="my-3">
                  <label for="quantity">Количество:</label>
                  <a class="minus-cart btn" pid={{item.product.id}}><i class="fas fa-minus-square fa-lg"></i></a>
                  <span id="quantity">{{item.quantity}}</span>
                  <a class="plus-cart btn" pid={{item.product.id}}><i class="fas fa-plus square fa-lg"></i></a>
                </div>
                <div class="d-flex justify-content-between">
                  <a href="#" class="remove-cart btn btn-sm btn-secondary mr-3" pid={{item.product.id}}>Удалить товар </a>
                  <p class="mb-0"><span><strong>₽ {{item.product.discounted_price}}</strong></span></p>
                </div>
              </div>
            </div>
          </div>
          <hr class="text-muted">
          {% endfor %}
        </div>
        </div>
      </div>

      <div class="col-sm-4">
        <div class="card">
          <div class="card-body">
            <h3>Итого к оплате</h3>
            <ul class="list-group">
              <li class="list-group-item d-flex justify-content-between align-items-center border-0 px-0 pb-0" >Сумма<span id="amount">₽ {{amount}}</span></li>
              <li class="list-group-item d-flex justify-content-between align-items-center px-0">Доставка<span>₽ 150.00</span></li>
              <li class="list-group-item d-flex justify-content-between align-items-center border-0 px-0 mb-3">
                <div>
                  <strong>Итого</strong> <small>(Включая доставку)</small>
                </div>
                <span id="totalamount"><strong>₽ {{totalamount}}</strong></span>
              </li>
            </ul>
            <div class="d-grid"><a href="{% url 'checkout' %}" class="btn btn-primary">Сделать заказ</a></div>
          </div>
        </div>
      </div>
      {% else %}
        <h1 class="text-center mb-5">Корзина пуста</h1>
    {% endif %}
  </div>
</div>

{% endblock main-content %}

2 ответа 2

0

Попробуйте сделать проверку, есть ли уже объект корзины для данного пользователя с данным товаром, если есть, то увеличивайте количество товара, если нет, то создавайте.

def add_to_cart(request):
    user = request.user
    product_id = request.GET.get('prod_id')
    product = Product.objects.get(id=product_id)
    card, created = Cart.objects.get_or_create(Q(product=product) & Q(user=user))
    if not created:
        card.quantity += 1
        card.save()
    return redirect('/cart')
6
  • К сожалению, в таком случае получаю ошибку при добавлении в корзину: TypeError at /add-to-cart/ 'Q' object is not iterable
    – Alexey
    18 мая в 7:05
  • Если меняю Q на словарь, то далее увеличивается только первый товар в корзине, остальные не добавляются
    – Alexey
    18 мая в 7:25
  • добавьте Q в импорте from django.db.models import Q 18 мая в 7:42
  • Решил данную проблему немного другим образом, def add_to_cart(request): user = request.user product_id = request.GET.get('prod_id') product = Product.objects.get(id=product_id) card, created = Cart.objects.get_or_create(user=user, product=product) if not created: card.quantity += 1 Cart.save() return redirect('/cart'). Спасибо Вам за помощь
    – Alexey
    18 мая в 7:56
  • Советую использовать Q object в будующем, достаточно мощный инструмент для сложных запросов. docs.djangoproject.com/en/4.2/topics/db/queries 18 мая в 8:15
0

Вот мое решение данной проблемы, только чуть-чуть другое:

def add_to_cart(request): 
user = request.user 
product_id = request.GET.get('prod_id') 
product = Product.objects.get(id=product_id) 
card, created = Cart.objects.get_or_create(user=user, product=product) 
if not created: 
    c = Cart.objects.get(Q(product=product) & Q(user=request.user))
    c.quantity += 1
    c.save()
return redirect('/cart')
1
  • добро пожаловать на Stack Overflow на русском! пожалуйста, постарайтесь оставлять чуть более развёрнутые ответы. дополнить ответ можно, нажав править 24 мая в 15:22

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.