Django:没有添加到购物车中的商品

时间:2015-04-18 09:39:21

标签: python django django-models django-forms django-admin

我在cart / views.py中有这个功能。如果没有购物车,一旦您尝试添加商品,它就会创建一个新购物车。但如果我进入管理员并查看购物车,则没有物品。我认为这与cart / views.py“if product:”部分有关。它不是根据购物车ID保存商品。

我如何更改以使其有效?

车/ views.py

def cart(request):
    context = {}
    template = 'cart/view_cart.html'
    try:
        cart_id = request.session['cart_id'] #try to get cart id from the session
    except:
        cart_id = False
    if cart_id:
        cart = Cart.objects.get(id=cart_id)
    else:
        cart = False
    return render(request, template, context)

def update_cart(request, id): #adds item in cart
    try:
        product = Product.object.get(id=id)
    except:
        product = False
    try:
        cart_id = request.session['cart_id']
    except:
        cart_id = False
    try:
        cart = Cart.objects.get(id=cart_id)
    except Cart.DoesNotExist:
        cart = Cart()
        cart.save()
        request.session['cart_id'] = cart.id


    if product:
        new_item, created = CartItem.objects.get_or_create(cart=cart, product=product)
        if created:
            new_item.cart = cart
            new_item.save()
            messages.success(request, 'cart item added')
    return HttpResponseRedirect('/cart/')

single.html(我点击添加项目的地方)

    {% block content %}

    <a href ='{% url "update_cart" product.id %}'>Add to Cart</a>
    <h1>{{ product }}</h1>
    {% for i in images %}
    <img src="{{ MEDIA_URL }}{{ i.image }}" width='500';/>

    {% endfor %}

车/ models.py

class Cart(models.Model):
    user = models.ForeignKey(User, null=True, blank=True)
    total = models.DecimalField(max_digits=50, default=0, decimal_places=2)
    active = models.BooleanField(default=True)
    timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
    updated = models.DateTimeField(auto_now_add=False, auto_now=True)

    def __unicode__(self):
        return str(self.id)

class CartItem(models.Model): #Creates items in the cart

    cart = models.ForeignKey(Cart) 
        product = models.ForeignKey(Product) 
        timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
        updated = models.DateTimeField(auto_now_add=False, auto_now=True)

        def __unicode__(self):
            return "%s" % (self.product.title)

车/ urls.py

    from django.conf import settings
    from django.conf.urls import patterns, include, url
    from django.contrib import admin

    urlpatterns = patterns('cart.views',
        url(r'^$', 'cart', name="cart"),
        url(r'^update_cart/(?P<id>.*)', 'update_cart', name="update_cart"),
    )

0 个答案:

没有答案