我正在link上关注有关创建购物车的教程。
我想自己进行一些调整,我试图在导航栏中添加一个能够显示否的购物车图标。购物车中的商品数和商品总数。
但是,只有当我在购物车的模板页面上时,此图标才能正确显示值,而在其余页面上则为空白。 (对我来说,会话范围似乎有问题)。
项目结构图-(https://academy.muva.tech/blog/wp-content/uploads/2018/05/cart.png)
购物车详细信息页面上的购物车图标图像(https://imgur.com/xyyqCNp)
其他页面上的购物车图标图像(https://imgur.com/jNGoiUK)
base.html
<div class="shopping-item">
<a href="{% url 'cart:cart_detail'%}">Cart - <span class="cart-amunt">{% with totail_items=cart|length %}Rs {{ cart.get_total_price }}</span> <i class="fa fa-shopping-cart"></i> <span class="product-count">{% if cart|length > 0 %}{{ cart.cart_item_count }}{% else %}0{% endif %}{% endwith %}</span></a>
</div>
detail.html (购物车页面)
{% extends 'shop/base.html' %}
{% load static %}
{% block title %}
Your Shopping Cart
{% endblock %}
{% block body_block %}
<div class="container">
<div class="row" style="margin-top: 6%">
<h2>Your Shopping Cart<br><br>
<span class="badge pull-right">
{% with totail_items=cart|length %}
{% if cart|length > 0 %}
My Shopping Order:
<a href="{% url "cart:cart_detail" %}" style="color: #ffffff">
{{ cart.cart_item_count }} item {{ totail_items|pluralize }}, Rs. {{ cart.get_total_price }}
</a>
{% else %}
Your cart is empty.
{% endif %}
{% endwith %}
</span>
</h2>
<table class="table table-striped table-hover">
<thead style="background-color: #5AC8FA">
<tr>
<th>Image</th>
<th>Product</th>
<th>Quantity</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="{% if product.image %} {{ product.image.url }} {% else %} {% static 'img/default.jpg' %} {% endif %}" alt="..." style="height: 130px; width: auto">
</a>
</td>
<td>{{ product.name }}</td>
<td>
<form action="{% url "cart:cart_add" product.id %}" method="post">
{% csrf_token %}
{{ item.update_quantity_form.quantity }}
{{ item.update_quantity_form.update }}
<input type="submit" value="Update" class="btn btn-info">
</form>
</td>
<td>
<a href="{% url "cart:cart_remove" product.id %}">Remove</a>
</td>
<td>Rs. {{ item.price }}</td>
<td>Rs. {{ item.total_price }}</td>
</tr>
{% endwith %}
{% endfor %}
<tr style="background-color: #5AC8FA">
<td><b>Total</b></td>
<td colspan="4"></td>
<td colspan="num"><b>Rs. {{ cart.get_total_price }}</b></td>
</tr>
</tbody>
</table>
<p class="text-right">
<a href="{% url "shop:product_list" %}" class="btn btn-default">Continue Shopping</a>
<a href="" class="btn btn-primary">Checkout</a>
</p>
</div>
</div>
{% endblock %}
cart.py (在应用程序“ cart ”内部)
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 cart_item_count(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
views.py (属于“购物车”)
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
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, quantity=cd['quantity'], update_quantity=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_quantity_form'] = CartAddProductForm(initial={'quantity': item['quantity'], 'update': True})
return render(request, 'cart/detail.html', {'cart': cart})
urls.py (“购物车”)
from django.conf.urls import url
from . import views
app_name = 'cart'
urlpatterns = [
url(r'^$', views.cart_detail, name='cart_detail'),
url(r'^add/(?P<product_id>\d+)/$', views.cart_add, name='cart_add'),
url(r'^remove/(?P<product_id>\d+)/$', views.cart_remove, name='cart_remove'),
]
urls.py (“项目”)
from django.contrib import admin
from django.urls import path
from django.conf.urls import url, include
from user_auth import views
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
path('admin/', admin.site.urls),
url(r'^$', views.index, name = 'index'),
url(r'^user_auth/', include('user_auth.urls')),
url(r'^special/$', views.special, name = 'special'),
url(r'^logout/$', views.user_logout, name = 'logout'),
url(r'^auth/', include('social_django.urls', namespace='social')),
path('cart', include('cart.urls')),
url(r'^shop/', include('shop.urls')),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
谢谢