将项目添加到购物车Django Python

时间:2016-03-22 06:31:36

标签: python django

EDIT 当我点击添加到购物车时,这是终端的输出

[22/Mar/2016 07:07:44] "GET /store/add/7 HTTP/1.1" 302 0
[22/Mar/2016 07:07:44] "GET /store/ HTTP/1.1" 200 4888

我有两个功能,一个添加物品到购物车,一个删除。

我认为问题是我的URL请求没有正确形成。所以我希望有一个比我更有经验的人向我解释预期的URL应该是什么。

我正在创建这样的网址,

url(r'^add/(\d+)', views.add_to_cart, name='add_to_cart'),  
    url(r'^remove/(\d+)', views.remove_from_cart, name='remove_from_cart'),
    url(r'^cart/', views.cart, name='cart'),

将项目添加到购物车的链接位于base.html文件中,如下所示,

  {% if request.user.is_authenticated %}
         <span class="storefront_add_to_cart">
             <a href="{% url 'add_to_cart' book.id %}">[Add to Cart]</a>
         </span>
         {% endif %}

因此,当您从购物车中添加或删除商品时,它会调用相应的功能。

Views.py

def add_to_cart(request,book_id):
        if request.user.is_authenticated():
            try:
                book = Book.objects.get(pk=book_id)
            except ObjectDoesNotExist:
                pass
            else :
                try:
                    cart = Cart.objects.get(user = request.user, active = True)
                except ObjectDoesNotExist:
                    cart = Cart.objects.create(user = request.user)
                    cart.save()
                    cart.add_to_cart(book_id)
                    return redirect('cart')
                else:
                    return redirect('index')


def remove_from_cart(request, book_id):
    if request.user.is_authenticated():
        try:
            book = Book.objects.get(pk = book_id)
        except ObjectDoesNotExist:
            pass 
        else:
            cart = Cart.objects.get(user = request.user, active = True)
            cart.remove_from_cart(book_id)
        return redirect('cart')
    else:
        return redirect('index')

当我点击添加到购物车时,网址看起来像这样(这给了我错误)

http://localhost:8000/store/add/4

当我点击从购物车中删除时,网址看起来像这样,但我没有收到任何错误。 (购物车中的商品保留,不会删除。)

http://localhost:8000/store/cart/%7B%20url%20'remove_from_cart'%20item.book.id%20%%7D

如果有帮助,这里是models.py

中的相应模型
class Cart(models.Model):
    user = models.ForeignKey(User)
    active = models.BooleanField(default=True)
    order_date = models.DateField(null=True)
    payment_type = models.CharField(max_length=100, null=True)
    payment_id = models.CharField(max_length=100, null=True)

    def __unicode__(self): 
            return "%s" % (self.user)

    def add_to_cart(self, book_id):
        book = Book.objects.get(pk=book_id)
        try:
            preexisting_order = BookOrder.objects.get(book=book, cart=self)
            preexisting_order.quantity += 1
            preexisting_order.save()
        except BookOrder.DoesNotExist:
            new_order = BookOrder.objects.create(
                book=book,
                cart=self,
                quantity=1
                )
            new_order.save()

            def __unicode__(self):
                return "%s" % (self.book_id)


    def remove_from_cart(self, book_id):
        book = Book.objects.get(pk=book_id)
        try:
            preexisting_order = BookOrder.objects.get(book=book, cart=self)
            if preexisting_order.quantity > 1:
                preexisting_order.quantity -= 1
                preexisting_order.save()
            else:
                preexisting_order.delete()
        except BookOrder.DoesNotExist:
            pass

3 个答案:

答案 0 :(得分:4)

让我们及时解决这个问题。

首先,你需要使用login_required decorator;您也不应该接受要添加到购物车中的无效书籍(您当前正在数据库级别检查,并且此错误未显示给客户)。

from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404

@login_required
def add_to_cart(request,book_id):
    book = get_object_or_404(Book, pk=book_id)
    cart,created = Cart.objects.get_or_create(user=request.user, active=True)
    cart.add_to_cart(book_id)
    return redirect('cart')

接下来,您需要修改模板,在其中生成链接以从购物车中删除商品。您的链接应该是:

<a href="{% url 'remove_from_cart' args=(item.book.id,) %}">Remove item</a>

在你的模型中,你有两个__unicode__方法,我认为这是复制粘贴中的一个错误,否则你需要删除第二个,因为它已经缩进到了来自add_to_cart

models.py方法

无论如何,你不需要这种方法,你应该在你的观点中保留整个逻辑。以下是修订后的方法:

from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404
from django.contrib import messages

from .models import Cart, BookOrder, Book

@login_required
def add_to_cart(request,book_id):
    book = get_object_or_404(Book, pk=book_id)
    cart,created = Cart.objects.get_or_create(user=request.user, active=True)
    order,created = BookOrder.objects.get_or_create(book=book,cart=cart)
    order.quantity += 1
    order.save()
    messages.success(request, "Cart updated!")
    return redirect('cart')

答案 1 :(得分:0)

您应该检查book_id的类型。这将是&#39; unicode&#39;。因此,比较Book.objects.get(pk=book_id)将不起作用。

您需要输入强制转换为整数。

使用:book_id = int(book_id)

之前

book = Book.objects.get(pk=book_id)

希望它有所帮助。

答案 2 :(得分:0)

我认为问题在于这里的缩进。

def add_to_cart(request,book_id):
    if request.user.is_authenticated():
        try:
            book = Book.objects.get(pk=book_id)
        except ObjectDoesNotExist:
            pass  
        else :
            try:
                cart = Cart.objects.get(user = request.user, active = True)
            except ObjectDoesNotExist:
                cart = Cart.objects.create(user = request.user)
                cart.save()
            cart.add_to_cart(book_id)
        return redirect('cart')
    else:
        return redirect('index')