Django模型不保存购物车项目

时间:2016-02-24 09:08:15

标签: django django-templates django-views

我已经创建了购物车视图,但我无法使用我的产品更新购物车。我从stackoverflow示例尝试了很多方法,但没有一个工作。我正在为Cart Application添加我的整个代码。 以下是我的Cart for Cart应用程序:

class CartItem(models.Model):
    cart = models.ForeignKey("Cart")
    item = models.ForeignKey(Variation)
    quantity = models.PositiveIntegerField(default=1)
    line_item_total = models.DecimalField(max_digits=10, decimal_places=2)

    def __unicode__(self):
        return self.item.title

    def remove(self):
        return self.item.remove_from_cart()

def cart_item_pre_save_receiver(sender, instance, *args, **kwargs):
    qty = instance.quantity
    if qty >= 1:
      price = instance.item.get_price()
      line_item_total = Decimal(qty) * Decimal(price)
      instance.line_item_total = line_item_total

pre_save.connect(cart_item_pre_save_receiver, sender=CartItem)

def cart_item_post_save_receiver(sender, instance, *args, **kwargs):
    instance.cart.update_subtotal()

post_save.connect(cart_item_post_save_receiver, sender=CartItem)

class Cart(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True)
    items = models.ManyToManyField(Variation, through=CartItem)
    timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
    updated = models.DateTimeField(auto_now_add=False, auto_now=True)
    subtotal = models.DecimalField(max_digits=50, decimal_places=2, default=60.00)

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

    def update_subtotal(self):
        print "updating..."
        subtotal = 0
        items = self.cartitem_set.all()
        for item in items:
            subtotal += item.line_item_total
        self.subtotal = subtotal
        self.save()

在我看来,我得到了:

from django.views.generic.base import View
from django.http import HttpResponseRedirect, Http404
from django.shortcuts import render, get_object_or_404
from django.views.generic.detail import SingleObjectMixin

from products.models import Variation
from .models import Cart, CartItem


# Create your views here.

class CartView(SingleObjectMixin, View):
    model = Cart
    template_name = "carts/view.html"

    def get_object(self, *args, **kwargs):
        self.request.session.set_expiry(0)           #for expire the session when we login, 0 means when we close browser session expire.
        cart_id = self.request.session.get("cart_id")
        if cart_id == None:                          # for cart id
            cart = Cart()
            cart.save()
            cart_id = cart.id
            self.request.session["cart_id"] = cart_id
        cart = Cart.objects.get(id=cart_id)
        if self.request.user.is_authenticated():        # for making user
            cart.user = self.request.user
            cart.save()
        return cart

    def get(self, request, *args, **kwargs):
        cart = self.get_object()
        item_id = request.GET.get("item")
        delete_item = request.GET.get("delete")
        if item_id:
            item_instance = get_object_or_404(Variation, id=item_id)
            qty = request.GET.get("qty", 1)
            try:
                if int(qty) < 1:                        #if qty <1 delete item
                    delete_item = True
            except:
                raise Http404
            cart_item = CartItem.objects.get_or_create(cart=cart, item=item_instance)[0]
            if delete_item:                             # for delete item
                cart_item.delete()
            else:
                cart_item.quantity = qty
                cart_item.save()
        context = {
            "object": self.get_object()                 # get_object from above
        }
        template = self.template_name
        return render (request, template, context)

在我的模板中,我添加了购物车的上下文:

{% extends 'home.html' %}

<script>
    {% block jquery %}
    $(".item-qty").change(function(){
        $(this).next(".btn-updated").fadeIn();
    });

    {% endblock %}
</script>

{% block content %}

<table class="table">
{% for item in object.cartitem_set.all %}
<tr>
    <form action="." method="GET" >
    <td>{{ item.item.get_title }}</td>
    <input type="hidden" name="item" value="{{ item.item.id }}" />                       <!-- for item id-->
    <td><input type="number" class="item-qty" name="qty" value="{{ item.quantity }}" />                   <!-- for quantity selection -->
    <input type="submit" class="btn-update btn btn-link" value="Updated item" style="display: None;" /></td>    <!-- for update the item-->
    <td>{{ item.line_item_total }}</td>
    <td class="text-right"><a href="{{ item.remove }}">X</a></td>
    </form>
</tr>
{% endfor %}

    <tr>
        <td colspan="4" class="text-right">Subtotal: {{ object.subtotal }}</td>
    </tr>
</table>

{% endblock %}

1 个答案:

答案 0 :(得分:0)

...
cart = models.ForeignKey("Cart", on_delete=models.CASCADE)
item = models.ForeignKey(Variation, on_delete=models.CASCADE)
...