我想将产品添加到我的购物车并显示购物车详细信息。我不明白为什么代码未在页面上显示详细信息?

时间:2018-12-03 07:19:11

标签: django python-3.x django-models django-forms

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 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

这是我的cart.py文件...

{% load static %}
{% block title %}
    Your Shopping Cart
{% endblock %}


{% block content %}
    <div class="container">
        <div class="row" style="margin-top: 6%">
        <h2>Your Shopping Cart
            <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">
                            {{ totail_items }} item {{ totail_items|pluralize }}, Kshs. {{ 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>kshs. {{ item.price }}</td>
                            <td>kshs. {{ 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>kshs. {{ cart.get_total_price }}</b></td>
                </tr>
                </tbody>
            </table>
        <p class="text-right">
            <a href="{% url "product_list" %}" class="btn btn-default">Continue Shopping</a>
            <a href="" class="btn btn-primary">Checkout</a>
        </p>
        </div>
    </div>
{% endblock %}

这是我的cart / templates / cart中的detail.html页面

<div class="row">
                        {% for product in products %}
                        <div class="col-sm-12 col-md-6 col-lg-4 p-b-50">
                            <!-- Block2 -->
                            <div class="block2">
                                <div class="block2-img wrap-pic-w of-hidden pos-relative">

                                      <img src="{{ MEDIA_URL }}{{ product.image.url }}" alt="IMG-PRODUCT" height="290" width="190">

                                        <div class="block2-overlay trans-0-4">
                                            <a href="#" class="block2-btn-addwishlist hov-pointer trans-0-4">
                                                <i class="icon-wishlist icon_heart_alt" aria-hidden="true"></i>
                                                <i class="icon-wishlist icon_heart dis-none" aria-hidden="true"></i>
                                            </a>
                                            <div class="block2-btn-addcart w-size1 trans-0-4">
                                                    <!-- Button -->
                                                    <form action="{% url "cart:cart_add" product.id %}" method="post">
                                                        {% csrf_token %}
                                                        {{ cart_product_form }}
                                                        <input type="submit" value="add to cart" class="flex-c-m size1 bg4 bo-rad-23 hov1 s-text1 trans-0-4">
                                                    </form>

                                            </div>
                                        </div>

                                </div>

                                <div class="block2-txt p-t-20">
                                    <a href="" class="block2-name dis-block s-text3 p-b-5">
                                        {{ product.description }}

                                    </a>

                                    <span class="block2-price m-text6 p-r-5">
                                        {{ product.price }}
                                    </span>
                                </div>
                            </div>
                        </div>
                        {% endfor %}
                    </div><!--end row-->

这是我的product / detail.html页面,在该页面上列出了我所有的产品,也是我要提交我的产品详细信息并将其添加到购物车的表格和底部。

from django.shortcuts import render, redirect, get_object_or_404
from django.views.decorators.http import require_POST
from product.models import Product
from .cart import Cart
from .forms import CartAddProductForm
@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, 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})
# Create your views here.

这是我的cart / views.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'),
]

这是我的cart / urls.py文件

1 个答案:

答案 0 :(得分:0)

您的详细信息页面不起作用,因为您的模板需要products,但是您仅在上下文中传递cart。要解决此问题,只需在呈现模板之前将products添加到上下文中即可。


def cart_detail(request):
    cart = Cart(request)
    products = []
    for item in cart:
        item['update_quantity_form'] = CartAddProductForm(initial={'quantity': item['quantity'], 'update': True})
        products.append(item)
    context = { 'cart': cart }
    context['products'] = products
    return render(request, 'cart/detail.html', context)
相关问题