1

您好,我正在编写我的电子商务 django 教程,由于某种原因,我的简单购物车计数不起作用。每次我添加到购物车时,我的 cart.html 中的 {{cart_item_count}} 都是 0

同样与此代码有关,这本书将我的 carts.py 设置为 cart.py,但由于该应用程序由于某种原因是 cart 不喜欢这样,所以我将我的 cart.py 重命名为“carts.py”,并从 cart import carts 执行此操作大车

Django不允许与应用程序同名的py文件吗???

帮助代码

carts.py 有一个函数 def cart_disinct_item_count(request) 返回在我的 views.py 中调用的计数以设置变量“cart_item_count”,该变量显示在我的 cart.html 页面中,但目前无论我的表单有什么都返回 0 .

我没有发布整个项目代码,但我想我得到了所有需要的相关信息。

谢谢

购物车.html

{% block content %}
<h1>Cart Page Here</h1>
Cart item count: {{cart_item_count }}
{% endblock %}

购物车视图.py

# Create your views here.
from django.shortcuts import render_to_response
from django.template import RequestContext
from cart import carts as cart

def show_cart(request, template_name="cart/cart.html"):
    cart_item_count = cart.cart_disinct_item_count(request)
    page_title = 'Shopping Cart'
    return render_to_response("cart/cart.html", locals(),
                          context_instance = RequestContext(request))

购物车项目模型

class CartItem(models.Model):
cart_id = models.CharField(max_length=50)
date_added = models.DateTimeField(auto_now_add = True)
quantity = models.IntegerField(default = 1)
product = models.ForeignKey('catalog.Product', unique = False)

class Meta:
    app_label = ''
    db_table = 'cart_items'
    ordering = ['date_added']

def total(self):
    return self.quantity * self.product.price
def name(self):
    return self.product.name
def price(self):
    return self.product.price

def get_absolute_url(self):
    return self.product.get_absolute_url()
def augment_quantity(self, quantity):
        """ called when a POST request comes in for a Product instance already in the shopping cart """
        self.quantity = self.quantity + int(quantity)
        self.save()

购物车.py

def get_cart_items(request):
    return CartItem.objects.filter(cart_id=_cart_id(request))

#add an item to the cart
def add_to_cart(request):    
    postdata = request.POST.copy()
    #get product slug from post data, return blank if empty
    product_slug = postdata.get('product_slug', '')
    #get quantity added, return 1 if empty
    quantity = postdata.get('quantity', 1)
    #fetch the product or return a missing page error
    p = get_object_or_404(Product, slug = product_slug)
    #get products in cart
    cart_products = get_cart_items(request)
    product_in_cart = False
    #check to see if item is already in cart
    for cart_item in cart_products:
        if cart_item.product.id == p.id:
            #update the quantity if found
            cart_item.augment_quantity(quantity)
            product_in_cart = True
        if not product_in_cart:
            #create and save a new cart item
            ci = CartItem()
            ci.product = p
            ci.quantity = quantity
            ci.cart_id = _cart_id(request)
            ci.save()
#returns the total number of items in the user's cart
def cart_disinct_item_count(request):
    return get_cart_items(request).count()

表格.py:

class ProductAddToCartForm(forms.Form):
quantity = forms.IntegerField(widget=forms.TextInput(attrs={'size':'2',
                              'value':'1', 'class':'quantity'}),
                              error_messages={'invalid': 'Please enter a valid quantity'},
                              min_value = 1)
product_slug = forms.CharField(widget = forms.HiddenInput())

#override the default __init__ so we can set the request
def __init__(self, request = None, *args, **kwargs):
    self.request = request
    super(ProductAddToCartForm, self).__init__(*args, **kwargs)

*编辑** 忘记添加显示产品并调用 add_to_cart 的视图:

#new product view, with POST vs GET detection

def show_product(request, product_slug, template_name = "catalog/product.html"):

p = get_object_or_404(Product, slug=product_slug)

categories = p.categories.all()
page_title = p.name
meta_keywords = p.meta_keywords
meta_description = p.meta_description
#need to evaluate the HTTP method
if request.method == 'POST':

    #add to cart....create the bound form
    postdata = request.POST.copy()
    form = ProductAddToCartForm(request, postdata)

    #check if posted data is valid
    if form.is_valid():
        #add to cart and redirect to cart page
        cart.add_to_cart(request)
        # if test cookie worked, get rid of it
        if request.session.test_cookie_worked():
            request.session.delete_test_cookie()

        url = urlresolvers.reverse('show_cart')
        return HttpResponseRedirect(url)
else:
    # it's a GET, create the unbound form. Note request as a kwarg
    form = ProductAddToCartForm(request = request, label_suffix = ':')


    #assign the hidden input the product slug
    form.fields['product_slug'].widget.attrs['value'] = product_slug
    #set the test cookie on our first GET request
    request.session.set_test_cookie()

    return render_to_response("catalog/product.html", locals(),   context_instance=RequestContext(request))
4

1 回答 1

2

发现错误 :) 缩进问题(愚蠢的 python) j/k 第一个是我的,第二个是正确的。得习惯这个。很容易被未经训练的眼睛忽视....

def add_to_cart(request):    
postdata = request.POST.copy()
product_slug = postdata.get('product_slug', '')
quantity = postdata.get('quantity', 1)
p = get_object_or_404(Product, slug = product_slug)
cart_products = get_cart_items(request)
product_in_cart = False
for cart_item in cart_products:
    if cart_item.product.id == p.id:
        cart_item.augment_quantity(quantity)
        product_in_cart = True
    if not product_in_cart:
        ci =  CartItem()
        ci.product = p
        ci.quantity = quantity
        ci.cart_id = _cart_id(request)
        ci.save()

这是书,它有效:

def add_to_cart(request):
postdata = request.POST.copy()
product_slug = postdata.get('product_slug','')
quantity = postdata.get('quantity',1)
p = get_object_or_404(Product, slug=product_slug)
cart_products = get_cart_items(request)
product_in_cart = False
for cart_item in cart_products:
    if cart_item.product.id == p.id:
        cart_item.augment_quantity(quantity)
        product_in_cart = True
if not product_in_cart:
    ci = CartItem()
    ci.product = p
    ci.quantity = quantity
    ci.cart_id = _cart_id(request)
    ci.save()
于 2012-12-31T04:08:42.840 回答