Проблема не быстрого добавления товара в корзину в django
Я создаю интернет-магазин на django, и столкнулся с проблемой. Проблема в том, что я могу добавить товар через страницу подробностей о товаре. Но я не могу сделать то же самое через кнопку Добавить в корзину прямо на главной странице сайта. И моя главная проблема заключается в том, что когда я нажимаю кнопку "Добавить в корзину" на главной странице. Я перенаправляюсь на страницу корзины, но без каких-либо товаров.
Это index.html в приложении магазина:
Это detail.html в приложении cart:
<table class="cart table">
<thead>
<tr>
<th>Image</th>
<th>Product</th>
<th>Count</th>
<th>Remove</th>
<th>Unit Price</th>
<th>Price</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:cart_add' product.id %}" method="post">
{{ item.update_product_count_form.product_count }}
{{ item.update_product_count_form.update }}
{% csrf_token %}
{{ item.update_product_count_form.update }}
<input type="submit" value="Update" class="btn">
</form>
</td>
<td><a href="{% url 'cart:cart_remove' product.id %}">Remove</a></td>
<td class="num">${{ item.price }}</td>
<td class="num">${{ item.total_price }}</td>
</tr>
{% endwith %}
{% endfor %}
<td>Total</td>
<td colspan="4"></td>
<td class="num">${{ cart.get_total_price }}</td>
</tbody>
</table>
<p class="text-right">
<a href="{% url 'shop:store' %}" class="btn">Continue shopping</a>
<a href="{% url 'shop:checkout' %}" class="btn">Checkout</a>
</p>
Это views.py в приложении shop:
from django.shortcuts import render, get_object_or_404
from . import models
from cart.forms import CartAddProductForm
def index(request):
product_list = models.Product.objects.all()[:5]
return render(request, 'index.html', {'product_list': product_list})
def checkout(request):
return render(request, 'checkout.html')
def product(request, pk):
product_detail = get_object_or_404(models.Product, id=pk)
cart_add_product_form = CartAddProductForm()
return render(request, 'product.html', {'product_detail': product_detail,
'cart_add_product_form': cart_add_product_form})
def store(request):
return render(request, 'store.html')
Это urls.py в приложении shop:
from . import views
from django.urls import path, include
from django.conf.urls.static import static
from django.conf import settings
app_name = 'shop'
urlpatterns = [
path('', views.index, name='index'),
path('checkout/', views.checkout, name='checkout'),
path('product/<int:pk>/', views.product, name='product'),
path('store/', views.store, name='store'),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Это models.py в приложении shop:
from django.contrib.auth.models import User
from django.db import models
from django.urls import reverse
class Product(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
create_time = models.DateTimeField(auto_now_add=True)
update_time = models.DateTimeField(auto_now=True)
image = models.ImageField(upload_to='images/product/%Y/%m/%d', blank=True)
price = models.DecimalField(max_digits=10, decimal_places=0)
class Meta:
ordering = ('create_time',)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('shop:product', args=[self.id])
class Order(models.Model):
customer = models.ForeignKey(User, on_delete=models.CASCADE)
order_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return str(self.id)
class OrderItem(models.Model):
order = models.ForeignKey(Order, on_delete=models.CASCADE)
product = models.ForeignKey(Product, null=True, on_delete=models.SET_NULL)
product_price = models.DecimalField(max_digits=10, decimal_places=0)
product_count = models.PositiveIntegerField()
product_cost = models.DecimalField(max_digits=10, decimal_places=0)
def __str__(self):
return str(self.id)
class Invoice(models.Model):
order = models.ForeignKey(Order, null=True, on_delete=models.SET_NULL)
invoice_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return str(self.id)
class Transaction(models.Model):
STATUS_CHOICES = (
('pending', 'Pending'),
('failed', 'Failed'),
('completed', 'Completed')
)
invoice = models.ForeignKey(Invoice, null=True, on_delete=models.SET_NULL)
transaction_date = models.DateTimeField(auto_now_add=True)
amount = models.DecimalField(max_digits=10, decimal_places=0)
status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='pending')
def __str__(self):
return str(self.id)
Это views.py в приложении cart:
from django.shortcuts import render, get_object_or_404, redirect
from django.views.decorators.http import require_POST
from cart.forms import CartAddProductForm
from .cart import Cart
from shop.models import Product
@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,
product_count=cd['product_count'],
update_count=cd['update'])
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_product_count_form'] = CartAddProductForm(initial={'product_count': item['product_count'],
'update': True})
return render(request, 'cart/detail.html', {'cart': cart})
Это urls.py в приложении cart:
from django.urls import path
from . import views
app_name = 'cart'
urlpatterns = [
path('', views.cart_detail, name='cart_detail'),
path('add/<int:product_id>/', views.cart_add, name='cart_add'),
path('remove/<int:product_id>/', views.cart_remove, name='cart_remove'),
]
Вы также можете посмотреть другие коды проекта в ссылке на картинке.