对象不保存到 Django 中的购物车

object not saving to cart in django

我正在尝试将对象添加到购物车,但没有添加任何东西。我对 Django 很陌生,感谢您的帮助。另外我认为错误与我的 cart_update 函数有关。在教程中,我是这样写的,但是当我查找这个问题时,我发现我应该使用 get_object_or_404。当我尝试这种方式时,我仍然无法将对象添加到购物车。

models.py

from django.db import models
import os
import random
from django.db.models import Q
from django.db.models.signals import pre_save, post_save
from django.urls import reverse 
from django.shortcuts import get_object_or_404

from .utils import unique_slug_generator

def get_filename_ext(filepath):
    base_name = os.path.basename(filepath)
    name, ext = os.path.splitext(base_name)
    return name, ext

def upload_image_path(instance, filename):
    new_filename = random.randint(1,233434234)
    name, ext = get_filename_ext(filename)
    final_filename = '{new_filename}{ext}'.format(new_filename=new_filename, ext=ext)
    return "products/{new_filename}/{final_filename}".format(new_filename=new_filename, final_filename=final_filename)


class ProductQuerySet(models.query.QuerySet):
    def active(self):
        return self.filter(active=True)

    def featured(self):
        return self.filter(featured=True, active=True)

    def search(self,query):
        lookups = (Q(title__icontains=query) | 
                   Q(description__icontains=query) |
                   Q(price__icontains=query) |
                   Q(tag__title__icontains=query)
                    )
        return self.filter(lookups).distinct()

class ProductManager(models.Manager):
    def get_queryset(self):
        return ProductQuerySet(self.model, using=self._db)

    def all(self):
        return self.get_queryset().active()

    def featured(self):
        return self.get_queryset().featured()

    def get_by_id(self,id):
        qs = self.get.queryset().filter(id=id)
        if qs.count() == 1:
            return qs.first()
        return None

    def search(self,query):
        return self.get_queryset().active().search(query)

class Product(models.Model):
    title           = models.CharField(max_length=120)
    slug            = models.SlugField(blank=True,unique=True)
    description     = models.TextField()
    price           = models.DecimalField(decimal_places=2,max_digits=20,default=10.99)
    image           = models.ImageField(upload_to='gallery',null=True,blank=True)
    featured        = models.BooleanField(default=False)
    active          = models.BooleanField(default=True)
    timestamp       = models.DateTimeField(auto_now_add=True)

    objects = ProductManager()

    def get_absolute_url(self):
#        return "/products/{slug}/".format(slug=self.slug)
         return reverse("products:detail", kwargs={"slug": self.slug})

    def __str__(self):
        return self.title

def product_pre_save_receiver(sender, instance, *args, **kwargs):
    if not instance.slug:
        instance.slug = unique_slug_generator(instance)

pre_save.connect(product_pre_save_receiver, sender=Product)

在这个视图中,我的 cart_update 函数出现了问题。

Cart/views.py

    from django.shortcuts import render, redirect, get_object_or_404
from products.models import Product
from .models import Cart


def cart_home(request):
    cart_obj, new_obj = Cart.objects.new_or_get(request)
    products = cart_obj.products.all()

    return render(request, 'carts/home.html', {})

def cart_update(request):
    product_id = 1 #request.POST.get('product_id')
#    print(Product.objects.get(id=1))
    if product_id is not None:
        try:
            product_obj = Product.objects.get(id=product_id)
        except Product.DoesNotExist:
            print("show message to user ,Product is gone")
            return redirect("cart:home")
        cart_obj, new_obj = Cart.objects.new_or_get(request)
        if product_id in cart_obj.products.all():
            cart_obj.products.remove(product_obj)
        else:    
            cart_obj.products.add(product_obj)
    #    return redirect(product_obj.get_absolute_url())
    return redirect("cart:home")

您还可以检查 new_obj 搜索项的出现次数,据我所知...

您可以在代码中改进一些地方:

1)如果商品不存在(你是"hardwiring"product_id1,可能是这样)使用logging,有情况print 声明是不够的。

2) 如果产品已经在购物车中,您将其移除,使购物车空着。您或许可以增加数量?

3) 条件 if product_id in cart_obj.products.all() 永远是 False cart_obj.products.all() 将 return Product 的查询集而不是 id 值,你有两个选择:

if product_id in cart_obj.products.values_list("id", flat=True)

if product_obj in cart_obj.products.all()

4) 我没有看到你的 'carts/home.html' 模板,但在你的视图 cart_home 中,你没有将产品添加到视图上下文中,顺便说一句,因为你可以访问篮子中的产品通过篮子本身(它们是相关的),你不需要行 products = cart_obj.products.all()。只需将 cart_obj 添加到视图上下文

def cart_home(request):
    cart_obj, new_obj = Cart.objects.new_or_get(request)
    return render(request, 'carts/home.html', {"cart": cart_obj}) 

并将如下代码写入您的模板:

<ul>
{% for product in cart.products.all %}
    <li>{{ product.title }}</li>
{% endfor %}
</ul>

希望您在检查其中一项时能发现错误,编码愉快!