Я пытаюсь создать компонент acart для моего сайта электронной коммерции. Появляется эта ошибка: ValueError в / cart / delete / 2 "" необходимо указать значение для поля "id", прежде чем можно будет использовать это отношение "многие ко многим".
views.py
from django.shortcuts import render, redirect, reverse
from django.urls import reverse_lazy
from .models import Cart
from products.models import Product
from django.shortcuts import get_object_or_404
def cart_home(request):
cart_obj, new_obj=Cart.objects.new_or_get(request)
return render(request, "carts/home.html", {"cart":cart_obj})
def addproduct(request, id):
productobj= get_object_or_404(Product, id=id)
shoppingcart=Cart()
shoppingcart.products.add(productobj)
shoppingcart.save()
return redirect("carts:home")
def removeproduct(request, id):
productobj= get_object_or_404(Product, id=id)
shoppingcart=Cart()
shoppingcart.products.remove(productobj)
shoppingcart.save()
return redirect("carts:home")
'' '' models.py '' '' *
from django.db import models
from django.conf import settings
from products.models import Product
from django.db.models.signals import pre_save, post_save, m2m_changed
User = settings.AUTH_USER_MODEL
class CartManager(models.Manager):
def new_or_get(self, request):
cart_id = request.session.get("cart_id", None)
qs = self.get_queryset().filter(id=cart_id)
if qs.count() == 1:
new_obj = False
print('cart id exists')
cart_obj = qs.first()
if request.user.is_authenticated and cart_obj.user is None:
cart_obj.user = request.user
cart_obj.save()
else:
print("new cart created")
new_obj = True
cart_obj= Cart.objects.new(user=request.user)
request.session['cart_id'] = cart_obj.id
return cart_obj, new_obj
def new(self, user=None):
user_obj = None
if user is not None:
if user.is_authenticated:
user_obj = user_obj
return self.model.objects.create(user=user_obj)
class Cart(models.Model):
user = models.ForeignKey(User, null=True, blank=True, on_delete="Cascade")
products = models.ManyToManyField(Product, blank=True, null=True)
total = models.DecimalField(default=0.00, max_digits=100, decimal_places=2)
updated = models.DateTimeField(auto_now=True)
timestamp = models.DateTimeField(auto_now_add=True)
objects = CartManager()
def __str__(self):
return str(self.id)
def m2m_changed_cart_receiver(sender, instance, *args, **kwargs):
products = instance.products.all()
total=0
for x in products:
total += x.price
print(total)
instance.total = total
m2m_changed.connect(m2m_changed_cart_receiver, sender=Cart.products.through)
'' '' carts: home.html '' ''
{% extends "base.html" %}
{% block content%}
<h1>Cart</h1>
{% if cart.products.exists %}
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Product Name</th>
<th scope="col">Product Price</th>
</tr>
</thead>
<tbody>
{% for product in cart.products.all %}
<tr>
<th scope="row">{{forloop.counter}}</th>
<td><a href="{{product.get_absolute_url}}">{{product.title}}</a>{% include "products/update_cart.html" %}</td>
<td>{{product.price}}</td>
</tr>
{% endfor %}
<tr>
<th colspan="2"></th>
<th><b>Total:</b>{{cart.total}}</th>
</tr>
</tbody>
</table>
{% else %}
<div class="lead"> Cart is empty</div>
{% endif %}
{% endblock %}
' '' 'cart-update.html
' '' '
{% if product in cart.products.all %}
<form action="{% url 'carts:remove' product.id %}"
method="post" style="display: inline;" onsubmit="window.mytest()">
{% csrf_token %}
<input type="hidden" name="product_id"
value="{{ product.id }}" />
<button type="submit" class="btn btn-default btn-sm">
<span class="fas fa-trash-alt"></span>remove?
</button>
</form>
{% else %}
<form action="{% url 'carts:add' product.id %}"
method="post" style="display: inline;" onsubmit="window.mytest()">
{% csrf_token %}
<input type="hidden" name="product_id"
value="{{ product.id }}" />
<button type="submit" class="btn btn-default btn-sm">
<span class="fas fa-trash-alt"></span>add to cart
</button>
</form>
{% endif %}
' '' 'так в продукте: подробный шаблон естьabutton Позвольте мне добавить этот продукт в корзину или удалить, если он есть, как решить вышеуказанную ошибку, а также как заставить кнопку перейти в определенный вид?заранее спасибо >>>