我目前正在开发一个在线商店,人们可以将产品添加到购物车。在我的 home html 文件中,如果产品未添加到购物车,我想显示“添加到购物车”按钮;如果添加产品,则显示“从购物车删除”按钮。但它无法正常工作。我现在收到“从购物车中删除”按钮。我的index.html:
{% extends 'base.html' %}
{% block content %}
<h1>Products</h1>
<div class="container-md">
<div class="row">
{% for product in products %}
<div class="col">
<div class="card-deck" style="width: 18rem;">
<img src="{{ product.image_url }}" class="card-img-top" alt="...">
<div class="card-body">
<a class="card-title" href="{% url 'detail-view' product.slug %}">{{ product.name }}</a>
<p class="card-text">${{ product.price }}</p>
{% if product in Cart.products.all %}
<a href="{% url 'add-to-cart' product.slug %}" class="btn btn-primary">Add to Cart</a>
{% else %}
<a href="{% url 'add-to-cart' product.slug %}" class="btn btn-primary">Remove from Cart</a>
{% endif %}
</div>
</div>
</div>
{% endfor %}
</div>
</div>
{% endblock %}
我的购物车的views.py:
from django.shortcuts import render, redirect, HttpResponseRedirect
from products.models import Product
from .models import Cart
from django.contrib import messages
from django.urls import reverse
def cart(request):
cart = Cart.objects.all()[0]
context = {"cart":cart}
template = 'shopping_cart/cart.html'
return render(request, template, context)
呼啦一阵风
相关分类