无法在电子商务应用程序中获取产品 ID -django

Not able to fetch product id in ecommerce application -django

views.py

    from django.shortcuts import render,redirect
    from .models import Cart
    from new_app.models import Product
    def cart_home(request):
                        
        cart_obj,new_obj=Cart.objects.new_or_get(request)
        products=Cart.objects.all()
        return render(request,'carts/home.html',{})
                    
                    
    def cart_update(request):
        print(request.POST)
        product_id=1
        print('id below')
        print(product_id) // not able to get the value of product id in console
        product_obj=Product.objects.get(id=product_id)
        cart_obj,new_obj=Cart.objects.new_or_get(request)
        if product_obj in cart_obj.products.all():
              cart_obj.products.remove(product_obj)
        else:
              cart_obj.products.add(product_obj)
        return redirect('home')

models.py(购物车)


    from django.db import models
    from django.conf import settings
    from new_app.models import Product
    from django.db.models.signals import pre_save,post_save,m2m_changed
    
    
    
    User=settings.AUTH_USER_MODEL
    
    class CartManager(models.Manager):
        def new_or_get(self,request):
            cart_id=request.session.get("cart_id",None)
            # qs=self.get_queryset().filter(id=cart_id)
            qs=self.get_queryset().only('products')
    
            print(qs)
            if qs.count()==1:
                    new_obj=False
                    cart_obj=qs.first()
                    print('cart obj below')
                    print(cart_obj)
                    if request.user.is_authenticated and cart_obj.user is None:
    
                        cart_obj.user=request.user
                        cart_obj.save()
    
    
            else:
                    cart_obj=Cart.objects.new_cart(user=request.user)
                    new_obj=True
                    request.session['cart_id']=cart_obj.id
            return cart_obj,new_obj
    
        def new_cart(self,user=None):
            user_obj=None
            if user is not None:
                if user.is_authenticated:
                    user_obj=user
            return self.model.objects.create(user=user_obj)
    
    class Cart(models.Model):
        user=models.ForeignKey(User,null=True,blank=True,on_delete=models.CASCADE)
        products=models.ManyToManyField(Product,blank=True)
        subtotal=models.DecimalField(default=0.00,max_digits=100,decimal_places=2)
    
        total=models.DecimalField(default=0.00,max_digits=100,decimal_places=2)
        timestamp=models.DateTimeField(auto_now_add=True)
        updated=models.DateTimeField(auto_now=True)
    
        objects=CartManager()
    
        def __str__(self):
            return str(self.id)
    
    
    def m2m_changed_cart_receiver(sender,instance,action,*args,**kwargs):
        print(action)
        if action=='post_add' or action=='post_remove' or action=='clear':
            products=instance.products.all()
            total=0
            for x in products:
                total += x.price
            if instance.subtotal != total:
                instance.subtotal=total
                instance.save()
    m2m_changed.connect(m2m_changed_cart_receiver,sender=Cart.products.through)
    
    
    def pre_save_cart_receiver(sender,instance,*args,**kwargs):
        if instance.subtotal>0:
            instance.total=instance.subtotal + 10
        else:
            instance.total=0.00
    
    pre_save.connect(pre_save_cart_receiver,sender=Cart)

update_cart.html

    <form method='POST' action='{% url 'update' %}' class="form ">{% csrf_token %}
      <input type="hidden"  name='product_id' value= "{{ product_id }}">
      {% if product in cart.products.all %}
        <button type="submit" class="btn btn-link">remove</button>
      {% else %}
        <button type="submit" class="btn btn-success">add to cart</button>
      {% endif %}
      </form>

终端输出:

    <QueryDict: {'csrfmiddlewaretoken': ['FMk2gTq6XXxZ2HU40I6h4b3WtPl59Drf1urwUNufDZUeSFPMzGNwU4L1QuGCiCbB'], 'product_id':
     ['']}>     -------- GETTING EMPTY DICTIONARY  INSTEAD OF GETTING PRODUCT ID i.e. 1
    id below
    1
    <QuerySet [<Cart: 13>]>

所以,除了 csrf 之外,我无法在那里获取产品 ID.... 我尝试单独打印产品 ID.. 为 1...(在输出中写在“id below”下)

  1. 我在处理电子商务网站的 CART 组件时遇到错误。问题是 product_id(与 PRODUCT 模型有外键关系)没有从 views.py 文件(在购物车中)中获取。我已经导入了 PRODUCT 模型。但是,当我尝试打印 product_id.
  2. 时,我得到了一个空字典
  3. 如您所见,我已经复制了终端的输出,即 csrf 令牌,其中有一个 product_id 的字典,它是空的。那里没有显示任何值。 如果我从 PRODUCT 应用程序的 views.py 中打印 3.The 产品 ID,则会打印它。 4.The 产品正在添加到购物车,正如我在管理员中检查的那样。

像这样更新您的代码:

def cart_update(request, **kwargs):
        product_obj=Product.objects.get(id=kwargs.get('product_id'))
        cart_obj,new_obj=Cart.objects.new_or_get(request)
        if product_obj in cart_obj.products.all():
              cart_obj.products.remove(product_obj)
        else:
              cart_obj.products.add(product_obj)
        return redirect('home')

并更新您的 urls.py,例如:

url(r'^add-to-cart/(?P<product_id>[-\w]+)/$', cart_update, name="cart_update"),

现在更新 update_cart.html 如:

<form method='POST' action='{% url 'update' %}' class="form ">{% csrf_token %}
  {% if product in cart.products.all %}
    <button type="submit" class="btn btn-link">remove</button>
  {% else %}
    <button type="submit" class="btn btn-success">add to cart</button>
  {% endif %}
  </form>

您是否检查过生成的 HTML 中隐藏输入的值中是否存在产品 ID?

如果不是这种情况,并且由于我看到您正在使用 product 对象,也许您应该在模板中使用 {{ product.id }} 而不是 {{ product_id }}(在第二行<input type="hidden" name='product_id' value= "{{ product_id }}">).